public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<Integer> array = new ArrayList<Integer>();
while(true){
System.out.println("请输入数据");
int number =sc.nextInt();
if(number!=0){
array.add(number);
}else{
break;
}
}
Integer[] i = new Integer[array.size()];
array.toArray(i);
Arrays.sort(i);
System.out.println("最大值为"+i[i.length-1]);
}
-------------------------------------------------------------------------------------
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
while(true){ Scanner sc = new Scanner(System.in);
System.out.println("请输入数据");
int number =sc.nextInt();
if(number!=0){
array.add(number);
}else{
break;
}
}
Integer[] i = new Integer[array.size()];
array.toArray(i);
Arrays.sort(i);
System.out.println("最大值为"+i[i.length-1]);
}
这里把Scanner sc = new Scanner(System.in);分别放在while语句外面和里面,并不影响结果,放在外面时,只创建一次对象,但为什么当进行while语句循环时都可以存储一个输入数据,和每次在while里面创建对象是等效的吗?求解?