且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scanner.hasNext上的无限循环,从文件中读取

更新时间:2023-01-14 13:50:59

好吧,根据

while(input.hasNext()) {
  if(input.hasNextInt()) {
    sum += input.nextInt();
  }
}

如果此令牌,您的扫描仪将不会使用下一个令牌不是 int ,你可以使用类似

Your scanner will not consume the next token if this token isn't an int, you can hilight this behavior with something like

int k=0;
while(input.hasNext()) {
  if(input.hasNextInt()) {
    sum += input.nextInt();
  } else {
    System.err.println("What ? It's not an integer...");
    if ( k < 1 ) {
      System.err.println("I'm gonna try again !");
      k++;
    } else {
      System.err.println("'"+input.next()+"' it's definitively not an integer");
      k=0;
    }
  }
}

最后,有很多解决方案,例如:

Finally, there are many solutions, for example :


  • 修改输入文件删除所有非整数标记

  • 消耗带的非整数令牌Scanner :: next()

  • Sanjeev的回答