1

我正在编写一个简单的程序来计算一组数字的平均值。您使用 获得数字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

}
4

5 回答 5

1

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

while(Input.hasNextInt()){

    count++;           

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

} // End of while
于 2012-10-09T19:06:33.380 回答
0

是的,魔术关键字是break;

于 2012-10-09T19:05:33.153 回答
0

break;声明可以被起诉以......好吧......打破迭代。例如,通过迭代,我的意思是你也可以摆脱 a for

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

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

   count++;           

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

 }

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

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:

while(keepIterating()){

   count++;           

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

}
于 2012-10-09T19:05:56.463 回答
0

问题是Scanner总是期望System.in. 您可以使用标记值跳出循​​环,例如-1

if (temp == -1) {
   break;
}
于 2012-10-09T19:10:12.187 回答
-2
public static void main(String[] args){

    Scanner Input = new Scanner(System.in);

    System.out.println("Enter # to end ");
    while( !Input.hasNextInt("#"))// return true if u input value = its argument
    {
        //ur code
    }//end while
于 2013-07-12T16:22:07.647 回答