我不断收到“线程“main”java.util.NoSuchElementException 中的异常”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22263906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:36:18  来源:igfitidea点击:

I keep getting "Exception in thread "main" java.util.NoSuchElementException"

javajava.util.scannernosuchelementexception

提问by Edax

So I'm trying to make a simple program in Java that reads a text file (from a command line argument) and the user can check to see if a number they input is in the text file.

所以我试图用 Java 编写一个简单的程序来读取文本文件(从命令行参数),用户可以检查他们输入的数字是否在文本文件中。

File inputFile = new File(args[0]);
Scanner scanman = new Scanner(inputFile); //Scans the input file
Scanner scanman_2 = new Scanner(System.in); //Scans for keyboard input
int storage[] = new int[30]; //Will be used to store the numbers from the .txt file

for(int i=0; i<storage.length; i++) {
  storage[i]=scanman.nextInt();
  }
System.out.println("WELCOME TO THE NUMERICAL DATABASE"+
                  "\nTO CHECK TO SEE IF YOUR NUMBER IN THE DATABASE"+
                  "\nPLEASE ENTER IT BELOW! TO QUIT: HIT CTRL+Z!");
while(scanman_2.hasNext()){
  int num_store = scanman_2.nextInt();
  boolean alert = false;
  for (int i=0; i<storage.length; i++) {
     if(storage[i]==num_store){
        alert=true;
        }
     }
  if (alert) {
     System.out.println("Yep "+num_store+" is in the database\n");
     }
  else {
     System.out.println("Nope, "+num_store+" is not in the database\n");
     }
  }
System.out.println("See ya!");                
  }
}

Everytime I attempt to run it I keep getting:

每次我尝试运行它时,我都会得到:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Database.main(Database.java:17)

I've done a program similar to this and had no problems. Does anyone know what I'm doing wrong?

我做了一个类似的程序,没有问题。有谁知道我做错了什么?

采纳答案by aliteralmind

You are repeatedly calling nextInt(), but not testing to see if there isa next int. Change this

您反复调用nextInt(),而不是测试,看看是否有下一个int类型。改变这个

for(int i=0; i<storage.length; i++) {
  storage[i]=scanman.nextInt();
}

to this

对此

for(int i=0; i<storage.length  &&  scanman.hasNext(); i++) {
  storage[i]=scanman.nextInt();
}

You'll need to determine if this is acceptable given your requirements, and if not, figure out why storage.length and the number of int-inputs are different than you expect.

您需要根据您的要求确定这是否可以接受,如果不能,请弄清楚为什么 storage.length 和 int-inputs 的数量与您的预期不同。

回答by jakerumbles

Adding the scannerName.hasNext()to my for loop fixed the issue.

添加scannerName.hasNext()到我的 for 循环解决了这个问题。