首页 > 解决方案 > Java while 循环帮助 - 嵌套 if else 语句

问题描述

我是 Java 的新手,并试图围绕金发姑娘和三只熊创建一个故事,在其中我向用户提出一系列问题,并且问题循环,直到给出预期的答案。它是针对一个类的,期望我们使用 while 循环和 if/嵌套 if else 语句来做到这一点。我已经设法对其进行了设置,以便在用户输入想要的答案时出现正确的消息,但是,如果他们输入错误的选择,则无法让问题循环。相反,它只是打印错误消息并结束程序。

谁能给我任何关于我哪里出错的提示/没有确切的修复只是一个基本的大纲将不胜感激。请假设该程序还有更多内容,但我不希望以后有任何抄袭自己的标记。

到目前为止,这是我的 if else 语句(我们使用 GTerm https://jupiter.csit.rmit.edu.au/~e58140/GTerm/doc/GTerm.html因此 gt.getInputString 等等)

String porridge1;

porridge1 = gt.getInputString("How hot was the porridge? Cold, hot, somewhere in the middle?");
//dialog box asking user question about porridge
        gt.println("\n" + "How did Golidlocks find the porridge? Too cold, too hot, or just right?");
// printed message about porridge temperature for user to follow
        if (porridge1.equalsIgnoreCase("cold") || porridge1.equalsIgnoreCase(hot")) {
            gt.showErrorDialog("Oh no. This porridge was too " + porridge1 + "!");
//if user input = cold or hot; error dialog box appears
            gt.println("Oh no! This porridge was too " + porridge1 + "!");
//if user input = cold or hot; print error message
        } else {
            gt.showMessageDialog("This porridge is just the right temperature!");
//if user types anything else, dialog box confirming correct choice to appear
            gt.println("How wonderful! This porridge is just right!");
//if any other input given (middle, warm, perfect, just right etc, print following message


标签: javaloopsif-statementwhile-loop

解决方案


据我所知,任何地方都没有循环,这就是它结束的原因。将该代码放在一个while循环中以使其保持运行,然后break在您希望它跳出循​​环时放置关键字。

while(true){
//Your code here
    if(condition...){}
    else(condition...){
       //Your code here
       break;
    }
}

也只是一个注释,通常注释代码位于您所指的代码行(或一侧)上方,而不是下方


推荐阅读