在数组中反转元素(Reversing elements in Arrays)

编程入门 行业动态 更新时间:2024-10-26 01:26:01
在数组中反转元素(Reversing elements in Arrays) public static void main(String[] args) { int[] HwArray = new int[10]; for (int i = 0; i < HwArray.length; i++) { HwArray[i] = i; } int count = 0; for (int i = 0; i < HwArray.length; i++){ HwArray[i] = (int) (100 + Math.random() * 100); System.out.print("HwArray[i]=" + HwArray[i]); } } { int[] reverse(int[] HwArray); { int[] reversed = new int[HwArray.length]; for (int i=0; i<HwArray.length; i++) { reversed[i] = HwArray[HwArray.length - 1 - i]; } return reverse; } } }

对不起,我还在学习。 我试图扭转所有元素的顺序,但我一直收到一个错误。 难道我做错了什么?

public static void main(String[] args) { int[] HwArray = new int[10]; for (int i = 0; i < HwArray.length; i++) { HwArray[i] = i; } int count = 0; for (int i = 0; i < HwArray.length; i++){ HwArray[i] = (int) (100 + Math.random() * 100); System.out.print("HwArray[i]=" + HwArray[i]); } } { int[] reverse(int[] HwArray); { int[] reversed = new int[HwArray.length]; for (int i=0; i<HwArray.length; i++) { reversed[i] = HwArray[HwArray.length - 1 - i]; } return reverse; } } }

Sorry, I'm still learning. I'm trying to reverse the order of all the elements, but I keep receiving an error. Am I doing something wrong?

最满意答案

说实话,你其实并不遥远。 reverse函数似乎可以正常工作,但是你有各种奇怪的语法错误,而且你甚至没有调用reverse方法。 尝试这样做:

在定义main的类中移动reverse方法。 如果你想从main直接调用它,你必须使它成为一个静态方法。

摆脱第17行和第25行的额外花括号。

声明reverse时,删除第18行中的分号。 它不应该在那里。

reverse方法试图返回一个名为reverse的变量。 这是方法的名称,你不能那样做。 我认为你的意思是reversed 。

在用随机数初始化数组后,实际上调用reverse方法。 然后再次打印数组以验证它是否有效。

注意你并没有在第11行打印出数组的值。这应该是System.out.println("HwArray[" + i + "]=" + HwArray[i]);

To be honest, you're actually not that far off. The reverse function actually seems to work okay but you have all kinds of weird syntax errors and you're not even calling the reverse method. Try doing this:

Move the reverse method inside the class where main is defined. If you want to call it directly from main you'll have to make it an static method.

Get rid of the extra curly braces on lines 17 and 25.

Remove the semicolon on line 18 when declaring reverse. It shouldn't be there.

The reverse method is trying to return a variable called reverse. That's the name of the method, you can't do that. I think you meant to return reversed.

Actually call the reverse method after you have initialized the array with random numbers. Then print the array out again to verify that it worked.

Notice that you're not actually printing out the values of the array on line 11. That should be System.out.println("HwArray[" + i + "]=" + HwArray[i]);

更多推荐

本文发布于:2023-08-03 07:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素   Reversing   elements   Arrays

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!