为什么这不起作用,但是当我将for循环从main方法移到反向方法时,它可以起作用吗?
public class ReverseArray
{
public static void main(String[] args)
{
int[] list = {1, 2, 3, 4, 5};
reverse(list);
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
}
public static void reverse(int[] list)
{
int[] temp = new int[list.length];
for (int i = 0; i < list.length; i++)
{
temp[i] = list[(list.length - 1) - i];
}
list = temp;
}
}
因为您要对方法内部的list进行更改,所以应该返回示例中显示的h的更新列表或更新原始列表本身
public static void main (String[] args) throws java.lang.Exception
{
int[] list = {1, 2, 3, 4, 5};
list=reverse(list);
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
}
public static int[] reverse(int[] list)
{
int[] temp = new int[list.length];
for (int i = 0; i < list.length; i++)
{
temp[i] = list[(list.length - 1) - i];
//list[i]=temp[i];
}
list = temp;
return list;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句