Search code examples
javagoto

illegal start of expression in using goto statement in java


I am trying to use goto statement to restart a player's turn but its not working.

if(spaceCheck(arr))
            {
            crack:
                System.out.println("Player "+player+"'s Turn:");
                System.out.print("Row : ");
                row=s.nextInt();
                System.out.print("Column : ");
                column=s.nextInt();

                if(indexValidate(arr,row,column))
                    {
                        arr[row][column]=player;
                    }
                else
                    {
                        goto crack;
                    }

Solution

  • goto is not a part of Java. Perhaps you were thinking of another language.

    As blurfus pointed out, even in languages that allow goto, you shouldn’t use it. It’s not good programming, because it encourages a lack of structure and “spaghetti code.”

    Use a loop instead:

    while (true) {
        System.out.println("Player "+player+"'s Turn:");
        System.out.print("Row : ");
        row=s.nextInt();
        System.out.print("Column : ");
        column=s.nextInt();
    
        if(indexValidate(arr,row,column)) {
            arr[row][column]=player;
            break;  // terminate while loop
        }
    }