簡體   English   中英

我如何貼標簽

[英]How do i put a label

我不明白應該在代碼中的哪個位置放置標簽“一”(我需要跳過 while 無限循環)

one:
while (true) {
    x = JOptionPane.showInputDialog(null, "Insert a data");
    y = y + Integer.parseInt(x);

    if (x == "ok") {
    break one;
    }
}

//here is where i need to get using the label
System.out.println("I did break");

誰能解釋一下我應該把標簽放在哪里?

您可以使用 do while 循環。

do{
 x =JOptionPane.showInputDialog(null, "Insert a data");
y = y + Integer.parseInt(x);
}while(!(x.equals("ok")));

//here is where i need to get using the label
System.out.println("I did break");

我認為標簽已經在正確的地方了。

根據Oracle Java 教程

break 語句終止帶標簽的語句; 它不會將控制流轉移到標簽。 控制流被轉移到緊跟在標記(終止)語句之后的語句。

在您的示例中,您甚至不需要標簽,因為您的 break 語句無論如何都會退出while(true)循環。 通常在嵌套循環時使用標簽。

好吧,我實際上自己找到了答案:錯誤在於,當嘗試將 int 的值分配給 y 時,如果它得到一個字符串 ('ok'),它會以錯誤終止。 所以我只需要在 if 序列之后移動那一行(並使用 equals 方法),現在它可以工作了。

one:
while (true) {
    x = JOptionPane.showInputDialog(null, "Insert a data");

    if (x.equals("ok")) {
    break one;
    }

    y = y + Integer.parseInt(x);
}

//here is where i need to get using the label
System.out.println("I did break");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM