3

所以我试图用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)

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

4

2 回答 2

5

您反复调用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 数量与您预期不同的原因。

于 2014-03-08T01:44:59.963 回答
0

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

于 2016-02-04T17:11:34.597 回答