I'm not too sure about this error as I cannot figure out what's going on. Through the debugger, I can see that the file is been successfully read, but on the last index, I get an error. Anyone know why?
try {
txtin = new Scanner(gameFile);
//String line;
while(txtin.hasNext()) {
for(int i = 0; i < 15; i++) {
Grid[i] = txtin.next();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (txtin != null)
txtin.close();
}
The error I get is:
Exception in thread "main" java.util.NoSuchElementException
How do I fix this?
Every time you call Iterator#next()
, it moves the underlying cursor forward. You are calling txtin.next()
in a for loop for 15 times. There may be a case where there are less than 15 token and the cursor went to a place that doesn't have such element Thus NoSuchElementException
Replace
while(txtin.hasNext()) {
for(int i = 0; i < 15; i++) {
Grid[i] = txtin.next();
}
}
with
int i=0;
while(txtin.hasNext()) {
Grid[i++] = txtin.next();
}
For the reasons described by Gagan Chouhan.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.