-1

I'm trying to access the array A outside the try function, but it says that the symbol cannot be found. How can I access the array A outside the try method ?

try {
        String filePath = "//Users/me/Desktop/list.txt";
        int N = 100000;
        int A[] = new int[N];

        Scanner sc = new Scanner(new File(filePath));

        for (int i = 0; i < N; i++)
        {
            A[i] = sc.nextInt();
        }
    } catch (IOException ioe) {
        System.out.println("IOException: " + ioe);
    }
lo1gur
  • 160
  • 2
  • 15

2 Answers2

2

You're running into the variable's scope. You can only use the variable in the scope where you created it. It's the same situation, for example, when you create a variable inside of a method -- you cannot access that variable from another method.

You have two options: either use the variable in the same scope (the try block) or declare the variable outside of that scope.

Option 1: the same scope

try {
  ...
  int A[] = new int[N];
  ...
  // use A here only
} catch (IOException ioe) { ... }
// A is no longer available for use out here

Option 2: declare it outside

int A[] = new int [N];
try {
  ...
} catch( IOException ioe) { ... }
// use A here
// but be careful, you may not have initialized it if you threw and caught the exception!
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
  • 1
    As a general good practice, you should additionally limit try/catches to only including the lines of code that might actually throw a caught exception. – alephtwo Jul 14 '17 at 19:56
  • Yes, you can still use the array @lo1ngru. But be careful, it might not have had its values populated. So when you access `A[ idx ]`, it may be the default int value (0) instead of the value in the file that you were expecting. If your file contains zeroes, this may lead to some confusion. – Roddy of the Frozen Peas Jul 14 '17 at 20:42
0

declare outside the block and allocate in the block:

int A[];

try {
        String filePath = "//Users/me/Desktop/list.txt";
        int N = 100000;
        A = new int[N];

        Scanner sc = new Scanner(new File(filePath));

        for (int i = 0; i < N; i++)
        {
            A[i] = sc.nextInt();
        }
    } catch (IOException ioe) {
        System.out.println("IOException: " + ioe);
    }
OldProgrammer
  • 12,050
  • 4
  • 24
  • 45