繁体   English   中英

我的 break 语句似乎工作不正常,执行后仍然循环一次

[英]My break statement doesn't seem to be working correctly, it still loops once after executing

首先让我说我是一个相对较新的编码员并且几乎没有经验,如果我的问题对某些人来说很容易,我很抱歉。 我需要编写一个使用 while 循环的程序,该程序将询问用户一个问题,如果他们有某个数字或高于该数字,他们将得到某个响应,如果没有,他们会被告知再试一次。 我想我大部分都做对了,但是每次我输入正确的数字时,它都不会立即中断并在停止之前循环一次。

public class TaffyTester
{
    public static void main(String[] args)
    {
        System.out.println("Starting the Taffy Timer...");
        System.out.print("Enter the temperature: "); 
        while (true)
        {
            Scanner input = new Scanner(System.in);
            int temp = input.nextInt();
            System.out.println("The mixture isn't ready yet.");
            System.out.print("Enter the temperature: ");
            if (temp >= 270)
            {
                System.out.println("Your taffy is ready for the next step!");
                break;
            }
        }
    }
}

我会改变顺序,所以它更合乎逻辑

    System.out.println("Starting the Taffy Timer...");
    Scanner input = new Scanner(System.in);
    int temp = 0;
    while (temp < 270)
    {
        System.out.println("The mixture isn't ready yet.");
        System.out.print("Enter the temperature: ");
        temp = input.nextInt();
    }
    System.out.println("Your taffy is ready for the next step!");

按照更有意义的顺序做事。 使while取决于您的情况。 满足条件后要做的事情应该在循环之后做。

结果

Starting the Taffy Timer...
The mixture isn't ready yet.
Enter the temperature: 800
Your taffy is ready for the next step!

暂无
暂无

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

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