Iram Shahed Iram Shahed - 1 month ago 7
Java Question

Returning back to the beginning of a loop using "continue" on Java

public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();

if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}


I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.

Answer

I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:

while (true) {
    int i = new Random().nextInt(prompts.length);
    System.out.println(prompts[i]);
    String input = Raybot.getInput();

    if (!checkPunc(input) && !checkCaps(input)) {
        System.out.println("Check your capitalization and your punctuation!");
    }
    else {
        System.out.println("Great grammar keep it up! Do you want to try again?");  
        input = Raybot.getInput();
        if (input.equals("no")) {
            break;
        }
    }
}

// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
Comments