-1

I need to help. I want to use label in java. Like label in c, but goto can't use in java. How move to label in java? Program :

ulang:
switch (menu){
case 1 : input(); goto ulang;
break;
}

How to change code to java code ?

Abdul Rahmat
  • 196
  • 9
  • You better use a loop. Seems you can use labels in a loop, see: https://stackoverflow.com/questions/26430630/how-to-use-goto-statement-correctly –  May 03 '18 at 04:50
  • Even in C, `goto` should be used rarely and only to go down, never up (like in your example). – DeiDei May 03 '18 at 04:52
  • Don't use `goto`. There are other ways to accomplish the same thing. – Code-Apprentice May 03 '18 at 05:13

4 Answers4

1

There is no goto in Java. I suggest to use loops.

while (true) {
  switch (menu){
    case 1 : input(); continue;
    break;
  }
  break;
}

Bellow does not work in Java as I expected, it makes a labeled switch statement and break + label breaks a switch, does not go to a label (thanks @xiaofeng.li and @YatiSawhney):

ulang:
switch (menu) {
  case 1 : input(); break ulang;
}

Read the SO article Is there a goto statement in Java?

273K
  • 29,503
  • 10
  • 41
  • 64
0

simply use looping if you want to make a repetition

do{
   /* code to display your menu here */
   switch(pilih){
      case 1 : input();break;
      case 2 : ..../*continue with your other selection*/
   }

}while(pilih!=5) // assume 5 is the exit choice
Jeffry Evan
  • 317
  • 1
  • 7
0

Java doesn't support goto. Although you can use the labelled break and continue in nested loops and switch statements, they are just there to tell the compiler which block of code you are referring to, not actually jumping to that location. For example, you can write:

ulang:
switch(menu) {
case 1: input(); break ulang; // break the switch labelled by 'ulang'
}

But it's just the same as

switch(menu) {
case 1: input(); break;
}
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
0

I won't recommend using labels(goto). (Just for the sake of knowledge)The following is the snippet that will let you understand the same. Break with a label will get you out of the outer loop which has got the label.

label: for( initialization ; condition ; modification ){

    for( initialization ; condition ; modification ){
        if(condition){
            break label;
        }
    }

}
Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19