Jordan Lee Burnes Jordan Lee Burnes - 6 months ago 23
Java Question

Looping Logic in Java

I have not programmed in a while and I am trying to get back into the swing of things and this is how far I have gotten. My question, is how do I loop the second question so that if the response is something besides a yes or no it asks the question again. I have tried putting a loop around the if statement, but whenever I try and get another response from the user it tells me I cannot use the variable, response, to do so. I feel this is an easy fix for I understand looping, but I am having a hard time wrapping my head around this specific issue, thank you in advance.

import java.util.Scanner;
public class Practice {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my simulation, please enter your name");
String name = input.nextLine();
System.out.println("Welcome " + name + " would you like to play a game?");
String response = input.nextLine();


boolean yes = new String("yes").equals(response.toLowerCase());
boolean no = new String("no").equals(response.toLowerCase());


if (yes){
System.out.println("Which game woudl you like to play?");
}else if (no){
System.out.println("Fine then, have a good day!");
}
else{
System.out.println("please enter either yes or no");
}
}

}

Answer

There are many ways to do it. Here's the first that came to mind:

while (true) {
    response = input.nextLine().toLowerCase();
    if (response.equals("yes") {
        System.out.println("Which game woudl you like to play?");
        break;
    } else if (response.equals("no") {
        System.out.println("Fine then, have a good day!");
        break;
    } else {
        System.out.println("please enter either yes or no");
    }
}
Comments