【发布时间】:2012-09-20 13:08:57
【问题描述】:
我正在尝试将字符串从一个类传递到另一个类,但我得到的结果是“null”。我想将字符串用户名从 LoginFrame 传递给 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);
}
}
登录框架:
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)并观察变量传递?
-
你没有显示你调用
loadSubjects()的代码。请问你能提供这个吗? -
'public void loadSubjects(){ String item;尝试{ System.out.println(用户名); 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, "无法加载主题!", "Error", JOptionPane.ERROR_MESSAGE); } }'