-1

I am trying to output the split contents of a .txt file.

Here is my code so far:

import java.io.FileReader;
import java.io.BufferedReader;

public class PassFail {

    public static void main(String[] args) {

        String path = "C:\\new_java\\Final_Project\\src\\student.txt";

        try {
            FileReader file = new FileReader(path);
            BufferedReader reader = new BufferedReader(file);

            String line = reader.readLine();
            reader.close();

            String[] values = line.split(" ");

            int nums[] = new int[values.length];

            for (int x = 0; x < values.length; x++) {
                nums[x] = Integer.parseInt(values[x]);
            }

        } catch (Exception e) {
            System.out.println("Error:" + e);
        }

        System.out.println(nums[1]);

    }

}

Question: Why am I getting the error "nums cannot be resolved to a variable" when trying to output num[2]? Furthermore, how can I fix this? To my knowledge I have already declared nums[] as a an int data type just before the for loop.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Robert Tossly
  • 613
  • 1
  • 6
  • 14
  • 3
    I indented your code for you. Now take a look at scope of `nums`. Can we access variables declared in inner code block from outer code block? – Pshemo Dec 02 '15 at 00:49

1 Answers1

2

Because nums is defined in the try block, and you try to access it outside the try.

Also, it's nicer if you use an IDE like IntelliJ or Eclipse. This will help you format the code, and more easily spot errors like this.

Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
  • Well that was a simple solution. I seriously couldn't find it online though, so thank you! – Robert Tossly Dec 02 '15 at 00:50
  • I am currently using Eclipse Galileo. lol. – Robert Tossly Dec 02 '15 at 00:51
  • 1
    @RobertTossly Then spam `Ctrl`+`Shift`+`F` or `Ctrl`+`I` whenever you can. – Pshemo Dec 02 '15 at 00:52
  • It helps if you know what to search on: http://stackoverflow.com/questions/11655020/why-does-a-try-catch-block-create-new-variable-scope. Also, press CTRL + SHIFT + F. It helps ;-) – Erik Pragt Dec 02 '15 at 00:52
  • Man, that is crazy, I wish I knew how to format before posting this. Also, I'd hate to ask a question in the comments, but my teacher wants us to add exception handling. Is it possible to add exception handling in this code without messing up the scope? – Robert Tossly Dec 02 '15 at 00:54
  • It's better to ask a new question and state exactly what you are looking for. "Messing up the scope" is a little too non-technical for me :) – Erik Pragt Dec 02 '15 at 00:56
  • I will do that now :) – Robert Tossly Dec 02 '15 at 00:57