user16713791
user16713791

Reputation: 129

java: cannot find symbol when using try/catch

I'm trying to collect input from the user, then if it's numeric – to turn it into an int, and if it's not – ask him to enter a numeric input

I'm using try/catch for this:

            System.out.println("Col: ");
            String temporary_col = sc.nextLine();

            try {
                int col = Integer.parseInt(temporary_col) - 1;
            } catch (NumberFormatException e) {
                System.out.println("Please enter a number");
                int col = sc.nextInt() - 1;
            }

and after that when I'm trying to use those variables:

field[col] = "X";

it returns this error:

java: cannot find symbol

Upvotes: 1

Views: 135

Answers (1)

f1sh
f1sh

Reputation: 11941

col is only visible in the block where you declare it. In your current code, you have 2 variables called col, one in the try block and one in the catch block. To fix this, declare the variable outside of the 2 blocks:

int col;
try {
  col = Integer.parseInt(temporary_col) - 1;
} catch (NumberFormatException e) {
  System.out.println("Please enter a number");
  col = sc.nextInt() - 1;
}

Upvotes: 1

Related Questions