Re: Need help stopping a loop

Posted 12 October 2008 - 11:18 PM

It stops but now it just keeps letting me enter numbers but when I clicked enter it still says enter an integer (or nothing to stop): . How do I get it to stop when someone clicks enter. I thought system.out.println() would work.

That way if the user enters anything other than the string "yes" the while loop will break and it will stop asking for integer input

Edit ::
Just something i noticed btw with your main code posted in the first post why are you taking numbers as entered by the user and storing them in String number ? When using JOptionPane you need to do this and then parse them to an Integer using Integer.parseInt(someStringRep);

So just a suggestion for you is to change your input to the use of Integers as you actually suggest in the user prompt... when you use "Enter an Integer (or nothing stop) : "

public static void main(String[] args) {
String str, turn = "yes";
int userEnteredInteger = 0;
//what it does
System.out.println("This program will average a series of numbers.");
Scanner keybd = new Scanner(System.in);
while (turn.equalsIgnoreCase("yes"))
{
System.out.print("Enter an integer : ");
// String number = keybd.nextLine(); // Instead of using this we will use the below
userEnteredInteger = keybd.nextInt();
// check if user wishes to continue
System.out.println("\nDo you wish to continue (yes / no ): ");
turn = keybd.next();
}
if(turn.equalsIgnoreCase("no"))
System.out.println();

Now if you are planning on actually adding each integer the user enters and adding them up then u need to add them as each is entered and keep count of how many are entered... Hence a variable int counter = 0; would be a good idea and then after each loop of the while loop increment counter++; (counter = counter + 1)... Also you will need to do something a little different with your variables... you will need to add each integer the user inputs to the total of the previous ones... for example

//in the while loop we have
System.out.println("Enter an Integer : ");
userEnteredInteger = keybd.nextInt()
//that would need modification so that each time the user enters something it is added to
//the previous total of the integers...
//so something like
userEnteredInteger += keybd.nextInt();
//this will take the user input and add it to the previous input's.
//after each input increment your counter also
counter++;

So say the user inputs
1 followed by 2, followed by 3
it would operate like this