Basic Loops stalling with While Statement Mystery
I am learning loops and wrote a very simple program to test my skills. In the first example, everything works fine. I added a second part to the loop in the second program and it no longer loops. I know this has to be easy but after hours of searching for an answer I decided to see if any of the experts out there could help. Thanks in advance for your help!
Gary
FIRST EXAMPLE - WORKS FINE
import java.util.*;
public class loopTest {
public static void main(String[] args){
String response;
Scanner keyboard = new Scanner(System.in);
System.out.println("Ready to start? Enter Y or N");
response = keyboard.nextLine();
while(response.equalsIgnoreCase("Y"))
{
System.out.println("in the loop");
System.out.println("Do again? Enter Y or N");
response = keyboard.nextLine();
}
System.out.println("out of loop");
}
}
SECOND EXAMPLE STALLS!! I added a second instruction in the loop. When it gets to the end of the loop it doesn't wait for the user to enter a number, goes back to the WHILE statement, then ends. :mad:
import java.util.*;
public class loopTest {
public static void main(String[] args){
String response;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.println("Ready to start? Enter Y or N");
response = keyboard.nextLine();
while(response.equalsIgnoreCase("Y"))
{
System.out.println("in the loop");
// New part to test loop
System.out.println("Enter a number");
number = keyboard.nextInt();
System.out.println(number);
System.out.println("Do again? Enter Y or N");
response = keyboard.nextLine();
}
System.out.println("out of loop");
}
}