简体   繁体   English

在Java上使用“ continue”返回到循环的开头

[英]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. 但是,每次我运行它时,它都会循环到结尾,甚至不要求输入。

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();

You are missing to actually accept any input 您缺少实际接受任何输入的信息

maybe 也许

System.out.println("Great grammar keep it up! Do you want to try again?");  
input = Raybot.getInput();

change if(input.equals("yes")) continue; 更改if(input.equals("yes")) continue;

to if(Raybot.getInput().equals("yes")) continue; if(Raybot.getInput().equals("yes")) continue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM