1

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

}
t0mm13b
  • 34,087
  • 8
  • 78
  • 110
Kuba Spatny
  • 26,618
  • 9
  • 40
  • 63

5 Answers5

1

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
Baz
  • 36,440
  • 11
  • 68
  • 94
Hayden
  • 2,818
  • 2
  • 22
  • 30
0

Yes, the magic keyword is break;

Baz
  • 36,440
  • 11
  • 68
  • 94
Roy
  • 974
  • 6
  • 11
0

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

}
Fritz
  • 9,987
  • 4
  • 30
  • 49
0

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;
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
-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
sayed
  • 1