Infinite loop on .hasNext()

Gabriel Colón :

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();

Anubhav :

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();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296125&siteId=1