hasNextInt不会返回false并退出循环

问题描述 投票:-2回答:1

我正在尝试将用户输入放入数组中,但hasNextInt()方法不会返回false并停止输入。

public static void main (String[] args) {

  Scanner in = new Scanner(System.in);

  int target = in.nextInt();
  while(in.hasNextInt()) {
     weights.insert(in.nextInt());
  }
  recKnapSack(target, 0);
}   
java input
1个回答
0
投票

Scanner.hasNextInt()在其缓冲区中遇到非整数字符时,它将返回false。但是,它可能会在读取提示时删除空格。所以Space+EnterEnter很可能不会停止循环。但任何其他角色都会。

由于您要输入任意数量的整数,因此必须指示用户完成后输入的内容。事实上,如果你正在编写一个控制台应用程序,那么总是要解释为什么程序在等待输入是一个好主意。

任何非整数都将停止循环条件。在这种情况下,语法将按原样运行,用户只需要一些指令:

System.out.println("Please enter the target");
int target = in.nextInt();
System.out.println("Enter weights. Type 'X' to stop");
while(in.hasNextInt()) {
© www.soinside.com 2019 - 2024. All rights reserved.