문제

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.

도움이 되었습니까?

해결책

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

다른 팁

while(true){
        System.out.println("Enter user Age");
        userAge = scInput.nextLine();
            if(tryParseInt(userAge)){
             return userInfo[row][1] = userAge;
             //you don't need break here because return at above line will make function to exit - break the loop
             //break; 
            }else{
                System.out.println("Please Enter an integer.");
                }
    }

Judge an inputting whether is an integer:

Scanner scanner = new Scanner(System.in);
try {
    userInfo[row][1] = scanner.nextInt());
    return;
} catch (InputMismatchException e) {
    System.out.println("Please enter a integer.");
}
finally{
    scanner.close();
}

and in your code, break sentence after a return sentence, so it's not reachable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top