简体   繁体   中英

how to make a loop of a switch statement with a label in java

it's quite simple but i don't seem to fegure it out here is my code

System.out.println("1=>do this \n2=> do that \n3=> blablabla \n4=> EXIT");


choose:{
int choix = s.nextInt();
switch (choix) {
case 1 : lper.addpersonne(); 
     break choose;
case 2 : lper.removepersonne();
     break choose;
case 3 : blalalalala

when it comes to execution

the "lper.addpersonne" works perfectly fine but after that i can't get the label where i can choose something else . it just stops

boolean loop = true;
while(loop){    
System.out.println("1=>do this \n2=> do that \n3=> blablabla \n4=> EXIT");
choose:{
    int choix = s.nextInt();
    switch (choix) {
    case 1 : lper.addpersonne(); 
        break choose;
    case 2 : lper.removepersonne();
     break choose;
    case 3 : blalalalala
    .... //What do you want more
    }
if(choix == 4){loop = false;}
}

}

Why not clean that code up a bit and use something along these lines?

int choix;
do {

    System.out.println("1=>do this \n2=> do that \n3=> blablabla \n4=> EXIT");
    choix = s.nextInt();
    switch (choix) {
    case 1 : lper.addpersonne(); 
        break;
    case 2 : lper.removepersonne();
        break;
    case 3 : blalalalala
        break;

} while (choix != 4);

This way you don't have to worry about the for loop, it repeats until the user wants to quit, and you don't have to use the pesky labels.

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