Java - 如何用 hasNext() 条件跳出 while? [英] Java - How to break out of while with hasNext() condition?

查看:27
本文介绍了Java - 如何用 hasNext() 条件跳出 while?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a simple program to calculate the average of a set of numbers. You get the numbers using Scanner, so I am using while loop with .hasNext() as a condition. However the loop is infinite.

是否可以在输入中不写一些诸如停止"之类的单词的情况下突破它?

Is it possible to break out of it without writing some certain word like "stop" in the input?

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; 语句可用于……嗯……中断迭代.例如,通过迭代,我的意思是你也可以摆脱 for.

The break; statement can be sued to... well... break out of an iteration. And by iteration I mean you can get out of a for too, for example.

您必须定义何时要中断迭代,然后执行以下操作:

You have to define WHEN do you want to break out of the iteration and then do something like this:

while(Input.hasNextInt(Input)){
   if(condition())
       break;

   count++;           

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

 }

否则,您可以创建一个辅助方法来定义迭代是否应该继续进行,如下所示:

Otherwise, you can make an auxiliary method that defines if the iteration should keep on going, like this one:

private boolean keepIterating(Scanner in) {
    boolean someOtherCondition = //define your value here that must evaluate to false
                                 //when you want to stop looping
    return Input.hasNextInt() && someOtherCondition;
}

您必须在 while 中调用的方法:

Method that you will have to invoke in your while:

while(keepIterating()){

   count++;           

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

}

这篇关于Java - 如何用 hasNext() 条件跳出 while?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆