简体   繁体   中英

Infinite loop on .hasNext()

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM