【问题标题】:Java while loop help - nested if else statement [closed]Java while循环帮助-嵌套if else语句[关闭]
【发布时间】:2021-04-01 07:13:52
【问题描述】:

我是 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


【问题讨论】:

  • 鉴于您还没有实现实际的循环,我理解您为什么不让它循环。所以:实现一个循环。
  • “它只是打印错误信息”什么错误信息?
  • porridge1.equalsIgnoreCase(hot") 我猜“hot”左边缺少的引号只是复制粘贴错误?
  • 你也少了一个括号')',在“cold”之后,用来关闭第一个if条件

标签: java loops if-statement while-loop


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2012-03-12
    • 2017-02-06
    • 2020-06-22
    • 2015-11-08
    • 1970-01-01
    相关资源
    最近更新 更多