Java - How to break out of while with hasNext() condition?

前端 未结 5 1371
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 04:11

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 .has

5条回答
  •  忘掉有多难
    2021-01-24 04:56

    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;
    }
    

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

提交回复
热议问题