Search code examples
javawhile-loopunreachable-code

break; line unreachable


String userAge;

    while(true){
        System.out.println("Enter user Age");
        userAge = scInput.nextLine();
            if(tryParseInt(userAge)){
             return userInfo[row][1] = userAge;
             break;
            }else{
                System.out.println("Please Enter an integer.");
                }
    }

Beginner here, Name is Reagan.

My problem is that my code doesn't compile because of "break;". It says it is an unreachable code. I feel i am doing something wrong here, and i'm almost certain it has to do with the variable type.. not sure how to do this. This is from a method that calls for the users age.

My goal is to pass a string through my tryParseInt() method to test and make sure the input data is a integer, but keep it as a string type variable.

I'm creating a multidimensional String array to store user's data. I.e. Name; age; location.


Solution

  • break statement after a return statement is unreachable because the function exits before break statement is reached. Remove break; and your code should compile.