0

Whenever I try to set the shipText array to a corresponding line within the file, it gives me

Exception in thread main: java.util.NoSuchElementException: No line found.

Why is this is happening? The error I continue to get no matter where I place the file in my workspace:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at shipPanel.<init>(shipPanel.java:28)
    at shipFrame.main(shipFrame.java:14)

This is my code for reading in the files name, shipsname-1.dat:

Scanner inputData; 
private String[] shipText = new String[138];
File infile =  new File("shipnames-1.dat");
inputData = new Scanner(infile);

for(int i = 0; i < shipText.length; i++)
{
    shipText[i] = inputData.nextLine();
    System.out.println(shipText[i]);
}
inputData.close();
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

you need to check for Scanner has next token or not ;

while(inputdata.hasNext()){
 //put you statement here
}
0

shipnames-1.dat maybe have 138 lines,so you should get 0 to 137,not 0 ~ 138, or you can do this

while (inputData.hasNext()) {
    System.out.println(inputData.nextLine());
}  
Jason D
  • 2,303
  • 14
  • 24
yabou
  • 1