My problem lies with trying to access Scanner scan created in one method from another method. It says it cannot find variable scan. I tried declaring a global Scanner scan, but it gave me an error, non static variable name cannot be referenced from a static context. How can I access this variable?
import java.util.*;
import java.io.*;
public class MyClass {
public static void myMethod() {
final File f = new File("file.txt");
Scanner scan = null;
try {
scan = new Scanner(f);
}
catch(FileNotFoundException ex) {
System.exit(0);
}
}
public static boolean anotherMethod() {
final String s = scan.next ();
if (s.equalsIgnoreCase ("true")) return true;
if (s.equalsIgnoreCase ("false")) return false;
throw new java.util.InputMismatchException ();
}
}
You’ve only declared the
scanvariable within theflowmethod. If you want to use that value within the other methods, you’ll need to take one of two courses of action:As all your methods are static, for the first option you’d need to declare it as:
However, currently the
flowmethod seems to do two radically different things:Scanner(but doesn’t actually use it)It looks to me like you should be creating the
Scannerin yourmainmethod (or in a new method which is called beforereadBoolean2D, anyway). You’re currently callingreadBoolean2Das the very first action of the program, trying to read from a variable which doesn’t exist, before anyScannerhas even been created.Note that none of this has anything to do with the
tryblock itself – it’s the fact that the variable is declared in a separate method which is the problem (and the timing of the method calls), not thetryblock.I would try to think of restructuring the program as:
I suspect you can actually get away with just local variables and parameters – the first method would return a
Scanner; the second method would take a Scanner and return the data it reads; the third method would take the data.