Reputation: 21
I am trying to read a file and extract the largest number. I want to read the file till the end but hasNext() keeps giving me true. When I tried changing this to hasNextInt(), it never went in even when my characters where integers. How can I get out of the loop and read my integers correctly? Help would be much appreciated.
int maxScore=0;
int score = 0;
Scanner scan = new Scanner("PacManHighScore");
while(scan.hasNext()) {
if(scan.hasNextInt()) {
score = scan.nextInt();
}
System.out.println(score);
if(score > maxScore) {
maxScore = score;
}
}
scan.close();
Upvotes: 0
Views: 204
Reputation: 89
You have forgot to skip non int value so you are stuck in an infinite loop.
Try the code below.
int maxScore=0;
int score = 0;
Scanner scan = new Scanner("PacManHighScore");
while(scan.hasNext()) {
if(scan.hasNextInt()) {
score = scan.nextInt();
}else{
scan.next();
}
System.out.println(score);
if(score > maxScore) {
maxScore = score;
}
}
scan.close();
Upvotes: 2