我的問題在於嘗試從另一種方法訪問在一個方法中創建的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 –