如果整数满足某些条件并分配给arrayList,那么从扫描仪获取整数的正确语法是什么?它应该循环并获取输入,直到我们插入"-1"。它停止然后我插入"q",但我需要它来处理某个整数。
Scanner sc = new Scanner(System.in);
while (-99 !== sc.nextLine() && sc.hasNextInt())
{
//do something Whi
}
这将循环,直到遇到 -1,并将元素添加到数组列表中。如果您需要任何帮助,请告诉我。
List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
// keep looping until -1 is encountered
while (true) {
int temp = scanner.nextInt();
if (temp == -1) {
break;
}
list.add(temp);
}
// Printing the array list
System.out.println(list);
// closing the scanner is important
scanner.close();
我不确定您的要求是什么,但是怎么样
Scanner sc = new Scanner(System.in);
while (true)
{
int numEntered = sc.nextInt ();
if (numEntered == -1) {
break;
}
// do something
}
您可能希望这样做:
Scanner sc = new Scanner(System.in);
int num;
do{
while (!sc.hasNextInt()){
sc.next();
}
num = sc.nextInt();
}while(num!=-1)
希望这有帮助!
sc 如果
引用了 Scanner 类的对象,而不是与 int 对象比较。 您必须在 while 循环中检查下一个 int 的值