簡體   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