Question

public static void getBooks()throws FileNotFoundException{

  Scanner input = new Scanner(bookFile);
  String line = input.nextLine();
  int bookNum = 1;

  while (input.hasNextLine()) {
     bookNum += 1;
     line = input.nextLine();
  }
  input.close();

  input = new Scanner(bookFile);
  line = input.nextLine();

  bookarray = new String[3][bookNum];

  for (int y = 0; y < bookNum; y++){
     bookarray [0][y] = line.substring(0,10);
     bookarray [1][y] = line.substring(11,15);
     bookarray [2][y] = line.substring(17,18);
     line = input.nextLine();
  }     

}

This code gives me this error:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at BookInventory1.getBooks(BookInventory1.java:64)
    at BookInventory1.main(BookInventory1.java:15)
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:838]

pointing at the last

  line = input.nextLine();

line. Can anyone help me?

Was it helpful?

Solution

you should check -> input.hasNext()

Check this tutorial scanner example or read the javadoc or checkout the specific javadoc for next ()

NoSuchElementException - if no more tokens are available

ex:

public static void getBooks()throws FileNotFoundException{

  Scanner input = new Scanner(bookFile);
  String line = input.nextLine();
  int bookNum = 1;

  while (input.hasNextLine()) {
     bookNum += 1;
     line = input.nextLine();
  }
  input.close();

  input = new Scanner(bookFile);
  if(scanner.hasNextLine(){
  line = input.nextLine();

  bookarray = new String[3][bookNum];

  for (int y = 0; y < bookNum; y++){
     bookarray [0][y] = line.substring(0,10);
     bookarray [1][y] = line.substring(11,15);
     bookarray [2][y] = line.substring(17,18);
     if(!line.hasNextLine()){break;}
     line = input.nextLine();
  } 
  }    

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top