martin shamasha martin shamasha -4 years ago 118
Java Question

Java: while loop, enter your next number or type "S" to stop

I want the user to stop entering numbers whenever they feel like it. When I run it, it does not work the way I want it to. Thanks for all the help in advance.

private static void whileLoop3()
System.out.printf("%n%nExecuting whileLoop3...%n%n");

int count=0;
int total=0;
int average;
int temp;

//while loop 10 times
while(count < 10)
//input number from user
temp = input.nextInt();
//add to total
total += temp; //same as total = total + temp
count++; //same as count = count + 10

System.out.printf("Count is %d%n", count);
average = total/count;
System.out.printf("The average of your numbers is %d%n", average);

System.out.printf("%nEnter your next number or \"S\" to stop: ");


Answer Source

I'd go for the use of a scanner, something like this:

Scanner scan = new Scanner(;

input = "";
while (!input.equals("S"){
   // do your stuff
   input = scan.nextLine();


Don't forget to import the java.util.Scanner package.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download