简体   繁体   中英

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

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, clicks, 635
2016-03-24, app_installs, 683
2015-04-05, favorites, 763
2016-01-22, favorites, 788
2015-12-26, clicks, 525
2016-06-03, retweets, 101
2015-12-02, app_installs, 982
2016-09-17, app_installs, 770
2015-11-07, impressions, 245
2016-10-16, impressions, 567


I have tried this
while (reader.hasNextLine()) but it is expecting another input.

You can break any loop in java using break keyword, in case of while loop:

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

}
// here the execution will go after the loop

The break can be used in any loop like for/while/do.

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

break keyword can be used for immediate stopping and escaping the loop. It is used in most of programming languages. There is also one useful keyword to slightly influence loop processing: continue . It immediately jumps to the next iteration.

Examples :

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

will print:

0
1
2
3

Continue:

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

will print:

0
1
2
3
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM