簡體   English   中英

如果我事先不知道行數,如何終止輸入循環?

[英]How can I terminate a loop for input if I don't know the number of lines beforehand?

如果我事先不知道行數,如何終止輸入循環?

2015-08,2016-04

2015-08-15,點擊,635
2016-03-24,app_installs,683
2015-04-05,最愛,763
2016-01-22,最喜歡的,788
2015-12-26,點擊,525
2016-06-03,轉推,101
2015-12-02,app_installs,982
2016-09-17,app_installs,770
2015-11-07,印象,245
2016-10-16,印象,567


我已經試過了
while (reader.hasNextLine())但它需要其他輸入。

您可以使用break關鍵字break Java中的任何循環,以防while循環:

while((reader.hasNextLine()) {
   boolean shouldBreak = ... // your code when it should break
   if (shouldBreak) break;

}
// here the execution will go after the loop

break可以在for / while / do之類的任何循環中使用。

while(true) { //or any other condition
    //do something
    if (userInput.equals("&") {
        break;
    }
}

break關鍵字可用於立即停止和轉義循環。 大多數編程語言都使用它。 還有一個有用的關鍵字可以稍微影響循環處理: continue 它立即跳到下一個迭代。

例子

int i = 0;
while (true) {
    if (i == 4) {
        break;
    }
    System.out.println(i++);
}

將打印:

0
1
2
3

繼續:

int i = 0;
while (true) {
    if (i == 4) {
        i++;
        continue;
    }
    if (i == 6) {
        break;
    }
    System.out.println(i++);
}

將打印:

0
1
2
3
5

暫無
暫無

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

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