簡體   English   中英

是否可以在while循環中分配變量?

[英]Is it possible to assign a variable in a while loop?

我正在尋找一種在 while 循環中使用掃描儀而不前進兩次的方法。

String desc = "";
while (!scanner.next().equals("END")) {
    desc = desc + scanner.next();
}           

如您所見,當在 while 循環的條件中和 while 循環本身內部調用scanner.next()時。 我希望它只推進掃描儀一次。 有沒有辦法做到這一點?

是的,這是可能的。 您還應該檢查Scanner的輸入中是否有更多令牌

String desc = "";
String next = null;
while (scanner.hasNext() && !(next = scanner.next()).equals("END")) {
    desc = desc + next;
}
    String temp = "";
    do {
        desc = desc + temp;
        temp = scanner.next();
    } while(!temp.equals("END"))

您可以使用 do-while 進行循環后條件檢查

暫無
暫無

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

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