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.

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?

有帮助吗?

解决方案

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

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top