-3
StartAgain:
    if(nit_arr.size() > 2)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
            goto StartAgain;
        }
    }

i want to regenerate a random number if last last two elements in the array lists are same and the list is having more than 2 elements in it. its not a loop to use break/continue. so how can i achieve this?

  • How any don't, instead stucfure your code to work without it using loops – MadProgrammer Oct 11 '15 at 03:41
  • Possible duplicate of [Alternative to a goto statement in Java](http://stackoverflow.com/questions/2430782/alternative-to-a-goto-statement-in-java) – resueman Oct 11 '15 at 03:56

2 Answers2

2

It's a horrible design decision, but you can use lableled statements in Java. In your case, you might use

continue StartAgain;

But you really should redesign your method. The JLS link for 14.7 says (in part),

Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
    for(bool again = nit_arr.size() > 2; again;)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
        }
        else{
             again = false;
             // do other stuff if needed
        }
    }

This is how we can achieve it, as well as most other constructions, without the need for a goto statement. Goto is usualy not recommended even in C/C++, because it breaks the structure of the code and makes it more difficult to track (by a human). Sure, everything in the compiled version will be translated into gotos, jumps, etc.

Another way using break; slightly less recommended but ok:

    while(nit_arr.size() > 2)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
        }
        else break;
    }
A.S.H
  • 29,101
  • 5
  • 23
  • 50