我試圖從一個類傳遞字符串到另一個類,但是我得到的結果是'null'。我想將LoginFrame中的字符串用戶名傳遞給HomeworkFrame;在java中將字符串從一個類傳遞到另一個類
HomeworkFrame:
public void loadSubjects(){
String item;
try{
System.out.println(username);
Scanner f = new Scanner (new FileReader (username + " " + "Subjects" + ".txt"));
while(f.hasNext()){
item = f.nextLine();
chSubjects.add(item);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Subjects cannot be loaded!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
LoginFrame:
public void loginUser(){
r = new Registration();
h = new HomeworkFrame();
l = new Login();
l.username = txtUser.getText();
l.password = txtPass.getText();
try{
String line;
boolean passwordFound = false ;
BufferedReader f = new BufferedReader(new FileReader(l.username + ".txt"));
while((line = f.readLine()) != null){
if(line.equals(l.password)){
passwordFound = true;
}
}
if(passwordFound){
h.username = l.username;
dispose();
m.setSize(700,600);
m.setLocation(100,100);
m.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
很顯然,我得到的錯誤 「對象不能加載」 作爲用戶名是空(我使用println方法檢查的話) 。
您是否嘗試調試代碼(例如使用eclipse)並觀察變量傳遞? – lilalinux
我使用JCreator。 – Matth963
你沒有顯示你調用'loadSubjects()'的代碼。請你能提供這個嗎? –