Jessica M. Jessica M. - 5 months ago 29
Java Question

User prompt using if statements

I'm trying to write a program that asks the user if they are pregnant. The problem I'm having is if the person enters "maybe" or any other response than "yes" or "no" I want the program to say "It's a yes or no question" then prompt the user to answer the question again. Instead it prints " It's a yes or no question" and "are you pregnant? " but it cannot accept another response. Is this the correct format for what I'm trying to do? In other words I want my program to keep asking the user if she is pregnant until I get a yes or no answer.

import acm.program.*;

public class AskProgram extends ConsoleProgram{
public void run(){

String answer = readLine(" are you pregnant? ");

if (answer.equals("yes")) {
println("Great! Congratulations ");
} else if (answer.equals("no")) {
println("keep trying it will happen.");
} else {
println("Its a yes or no question");
readline("are you pregnant? ");
}
}
}

Answer

This will repeat the block until the user inputs either "Yes" or "No":

String answer = "";
while (!answer.equalsIgnoreCase("yes") && !answer.equalsIgnoreCase("no")) {
    answer = readLine("Are you pregnant?");
    if (answer.equalsIgnoreCase("yes")) {
        println("Great! Congratulations ");
        break;
    } else if (answer.equalsIgnoreCase("no")) {
        println("keep trying it will happen."); 
        break;
    } else {
        println("Its a yes or no question");
        readline("are you pregnant? ");
    }    
}