【问题标题】:I keep getting "Exception in thread "main" java.util.NoSuchElementException"我不断收到“线程“主”java.util.NoSuchElementException中的异常”
【发布时间】:2014-03-08 01:42:58
【问题描述】:

所以我正在尝试用 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!");                
  }
}

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

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)

我已经完成了一个类似的程序并且没有任何问题。有谁知道我做错了什么?

【问题讨论】:

    标签: java java.util.scanner nosuchelementexception


    【解决方案1】:

    您反复调用nextInt(),但没有测试是否有 下一个int。改变这个

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

    到这里

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

    根据您的要求,您需要确定这是否可以接受,如果不可以,请找出 storage.length 和 int-input 数量与您的预期不同的原因。

    【讨论】:

    • 谢谢。这解决了它。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-02
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      相关资源
      最近更新 更多