如何修复无法从静态上下文中引用的非静态变量
how to fix non-static variable this cannot be referenced from a static context
我在 class
中有这个字符串声明
String username,ICNo,studentID,password;
我有这个方法可以从 txt 文件中读取,因此可以分配它从字符串中获得的变量
static void createFound(String ID){
try {File myObj = new File(infoFile);
Scanner sc = new Scanner(myObj);
boolean notFound=true;
while (sc.hasNextLine()&¬Found) {
String data = sc.nextLine();
String[] userInfo = data.split(Character.toString(seperator));
if(userInfo[2].equals(ID)){
notFound=false;
username=userInfo[0];
ICNo=userInfo[1];
studentID=userInfo[2];
password=findPass(userInfo[0]);
// System.out.println(foundUser.username);
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
我在线上有一个错误(非静态变量不能从静态上下文中引用)
username=userInfo[0];
ICNo=userInfo[1];
studentID=userInfo[2];
password=findPass(userInfo[0]);
我已将静态声明添加到我声明变量的行,但发现如果我这样做,returns当我这样做时一片空白
jLabel9.setText(student.studentID);
从方法 createFound() 中删除静态变量或使变量成为静态变量。
我在 class
中有这个字符串声明String username,ICNo,studentID,password;
我有这个方法可以从 txt 文件中读取,因此可以分配它从字符串中获得的变量
static void createFound(String ID){
try {File myObj = new File(infoFile);
Scanner sc = new Scanner(myObj);
boolean notFound=true;
while (sc.hasNextLine()&¬Found) {
String data = sc.nextLine();
String[] userInfo = data.split(Character.toString(seperator));
if(userInfo[2].equals(ID)){
notFound=false;
username=userInfo[0];
ICNo=userInfo[1];
studentID=userInfo[2];
password=findPass(userInfo[0]);
// System.out.println(foundUser.username);
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
我在线上有一个错误(非静态变量不能从静态上下文中引用)
username=userInfo[0];
ICNo=userInfo[1];
studentID=userInfo[2];
password=findPass(userInfo[0]);
我已将静态声明添加到我声明变量的行,但发现如果我这样做,returns当我这样做时一片空白
jLabel9.setText(student.studentID);
从方法 createFound() 中删除静态变量或使变量成为静态变量。