有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无限循环。hasNext()

我试图读取一个文件并提取最大的数字。我想把文件读到最后,但hasNext()一直告诉我是真的。当我尝试将其更改为hasNextInt()时,即使我的字符中包含整数,它也从未进入。我怎样才能走出循环并正确读取整数?非常感谢您的帮助

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


共 (1) 个答案

  1. # 1 楼答案

    你忘了跳过非int值,所以你陷入了一个无限循环

    试试下面的代码

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