所以我试图在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)
我做了一个与此相似的程序,没有任何问题。有谁知道我做错了什么?
答案 0 :(得分: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-inputs的数量与您预期的不同。
答案 1 :(得分:0)
将scannerName.hasNext()
添加到my循环修复了问题。