Java - 如何用 hasNext() 条件打破 while ?

标签 java while-loop

我正在编写一个简单的程序来计算一组数字的平均值。您使用 Scanner 获取数字,因此我使用 while 循环和 .hasNext() 作为条件。然而,循环是无限的。

是否可以在不输入某些特定单词(例如“停止”)的情况下摆脱它?

public class main {

    public static void main(String[] args){

        Scanner Input = new Scanner(System.in);
        int count = 0;
        int temp;
        int sum = 0;

        while(Input.hasNextInt()){

           count++;           

           temp = Input.nextInt();
           sum += temp;
           System.out.println(temp);
           System.out.println(count);           

        } // End of while

        double average = sum / count;
        System.out.println("The average is: " + average);

    } // End of method main

}

最佳答案

您可以简单地使用关键字 break 来停止 while 循环:

while(Input.hasNextInt()){

    count++;           

    temp = Input.nextInt();
    sum += temp;
    System.out.println(temp);
    System.out.println(count); 
    break;          

} // End of while

关于Java - 如何用 hasNext() 条件打破 while ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12806672/

相关文章:

java - 20 秒后退出 while 循环

perl - 使用 Filehandle 和 while 循环定义的用法

javascript - 我的 if else 语句中的变量数字没有更新

java - 无法从 Scriptlet 中的方法将值返回到屏幕

java - 如何设置 AWS APIGateway 阶段的 CloudWatch 设置

java - libgdx-freetype 如何以正确的字母间距缩放字体?

python - 字符串格式 .format 到变量

java - 延迟接受爬山算法

java - 安卓库 : activeandroid index and unique annotation not available

php - 修改代码以获取旧帖子上方最近评论的帖子