为什么列表只添加某些数字?
问题描述:
我想通过询问用户输入来编译int列表。但是,由于某些原因,代码仅将偶数添加到列表中。此外,while循环仅在第二次输入999时停止。代码如下:为什么列表只添加某些数字?
import java.util.*;
public class hw3 {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> pre = new ArrayList<Integer>();
while (input.nextInt() != 999) {
pre.add(input.nextInt());
}
}
}
我不知道我在做什么错。请指出我的错误。
答
nextInt()
被调用两次,一次在循环之前,然后在while循环中。
你需要做的是这样的:
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> pre = new ArrayList<Integer>();
int in;
while ((in = input.nextInt()) != 999) {
pre.add(in);
}
}
答
您在循环的每次迭代中调用input.nextInt()两次。
只需调用一次,缓存结果并在添加到数组时使用它。