Java - 如何在使用hasNext()条件时突破? [英] Java - How to break out of while with hasNext() condition?

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

问题描述

我正在编写一个简单的程序来计算一组数字的平均值。您使用 Scanner 获取数字,因此我使用循环使用 .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; 语句可以起诉......嗯......突破迭代。通过迭代我的意思是你也可以从中获取,例如。

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.

你必须定义WHEN你想要突破迭代,然后做这样的事情:

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(keepIterating()){

   count++;           

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

}

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

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