简体   繁体   English

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

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

Let me start off by saying that I am a relatively newer coder and have little to no experience, I'm sorry if my questions may be easy to some people.首先让我说我是一个相对较新的编码员并且几乎没有经验,如果我的问题对某些人来说很容易,我很抱歉。 I need to write a program that uses a while loop that will ask the user a question and if they have a certain number or above it, they will get a certain response, if not, they are told to try it again.我需要编写一个使用 while 循环的程序,该程序将询问用户一个问题,如果他们有某个数字或高于该数字,他们将得到某个响应,如果没有,他们会被告知再试一次。 I think I've done most of it right but everytime I put in the correct number, it doesn't break immediately and loops back one time before stopping.我想我大部分都做对了,但是每次我输入正确的数字时,它都不会立即中断并在停止之前循环一次。

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;
            }
        }
    }
}

I would change the order so it is more logical我会改变顺序,所以它更合乎逻辑

    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!");

Do things in the order that makes more sense.按照更有意义的顺序做事。 Make the while dependdant on your condition.使while取决于您的情况。 Things that are to be done after the condition is met should be done after the loop.满足条件后要做的事情应该在循环之后做。

Result结果

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