对不起,我还在学习。 我试图扭转所有元素的顺序,但我一直收到一个错误。 难道我做错了什么?
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]);
更多推荐
发布评论