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

久未见 提交于 2019-12-02 03:26:26

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

}
Hayden

You could simply use the keyword break to stop the while loop:

while(Input.hasNextInt()){

    count++;           

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

} // End of while
Roy

Yes, the magic keyword is break;

The problem is that Scanner will always expect an integer from System.in. You could break out of the loop using a sentinal value e.g. -1:

if (temp == -1) {
   break;
}
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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!