我的问题在于尝试从另一种方法访问在一个方法中创建的Scanner scan
。它说它无法找到变量扫描。我试过宣布全球Scanner scan
,但它给了我一个错误,non static variable name cannot be referenced from a static context
。我怎样才能访问这个变量?尝试使用另一种方法尝试{}中的扫描仪? --Java
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();
}
}
让它作为一类提交'私人扫描仪scan = null;' –
刚刚尝试过,Try {}中的'scan'给了我错误“非静态变量扫描不能从静态上下文中引用”。 :/ –
也张贴在这里:http://www.daniweb.com/software-development/java/threads/385513/1660807#post1660807 –