1

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.

Reagan B
  • 23
  • 2

3 Answers3

10

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

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • I've removed the break. Code runs, however it runs through the entire loop before testing my condition. Ideally i would like it to display the else statement if my condition is false. – Reagan B Mar 25 '13 at 02:50
  • If you want to loop your conditions again, then don't use the return or break statement in the loop. And when next time program asks for input then enter some characters and you should see your else condition being executed. But remember, removing break or return in this while-loop makes it an infinite loop! – Himanshu Bhardwaj Mar 25 '13 at 04:27
0
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.");
                }
    }
nommyravian
  • 1,316
  • 2
  • 12
  • 30
0

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.

Scy
  • 488
  • 3
  • 11