-1

What I am trying to do is read data from a file and only print the integers out. I am trying not to use an arraylist for this, It works flawlessly with an arraylist but I'm trying to do this another way.The problem is my code is showing the error the scanner is not a symbol.

error: cannot find symbol
              data[i++] = scannernextInt();
                          ^

error: cannot find symbol
              scanner.next();
              ^

Can you explain why this error is showing up?


What I have currently:

 public static void main(String[] args) {

    int[] data = new int[8];
    int i = 0; 

    try
    {
       Scanner scanner = new Scanner(new File("data.txt"));
    }
    catch (FileNotFoundException e) 
    {
       System.out.println(" File does not exist.");
       scanner = null;
    }        


     while (scanner.hasNext())
        {
           if(scanner.hasNextInt())
           {
              data[i++] = scannernextInt();
              System.out.print(data[i]);
           }
           else
           {
              scanner.next();
           }
        }

1 Answers1

1

The compiler is defining the scope of the Scanner object inside of the try catch block.

You can either raise the Scanner definition out of the try catch, or move the logic that uses the scanner inside of the try catch.

For the first error you're mission the access operator it should look like this (choosing the first option for the scanner issue)

public static void main(String[] args) {

    Scanner scanner;
    int[] data = new int[8];
    int i = 0; 

    try {
       scanner = new Scanner(new File("data.txt"));
    } catch (FileNotFoundException e) {
       System.out.println(" File does not exist.");
       scanner = null;
    }        


     while (scanner.hasNext()) {
       if(scanner.hasNextInt()) {
          data[i++] = scanner.nextInt();
          System.out.print(data[i]);
       } else {
          scanner.next();
       }
     }
}
jdavison
  • 322
  • 1
  • 9
  • With both solutions, the error cannot find symbol scanner "data[i++] = scanner.nextInt();" is still there. I don't know why it doesn't see the scanner definition outside of the try block? I moved the while loop in the try block as well with the same message. – LandscapeGolfer Sep 14 '18 at 01:43