这是我的代码:
public static String currentStudent = "";
public void login() {
boolean studentLoggedOn = false;
Student student = new Student();
PC_Dialog dialog = new PC_Dialog("Enter Login Information", "Student ID, Password-", "OK");
dialog.choice();
String studentID = dialog.getField(1);
String password = dialog.getField(2);
student = (Student) projectSystem.studentFile.retrieve(studentID);
if (studentID != null) {
if (password.equals(student.password)) {
currentStudent = studentID;
studentLoggedOn = true;
studentRun();
}
}
if (!studentLoggedOn) {
JOptionPane.showMessageDialog(null, "Either the user name or the password were incorrect");
login();
}
}
完成所有这些后,“currentStudent = studentID;
”似乎对currentStudent String
没有任何影响?
答案 0 :(得分:2)
您的问题不完整,但如果我不得不猜测,我会说您在代码中的其他位置引用了currentStudent。由于字符串不可变,并且赋值运算符也不会改变对象,因此该引用不会改变。
例如:
String one = "some string";
String two = one;
one = "another";
System.out.println(one);
System.out.println(two);
将输出
another
some string
尝试阅读Java引用和字符串赋值。
根据问题作者的要求,这是一个完成我认为他想要的例子。
public class Session {
private String currentUserId = null;
public void setCurrentUserId( String id ) {
currentUserId = id;
}
public String getCurrentUserId() {
return currentUserId;
}
// Other session related information
//...
}
使用Session类如下。
public class MyApp {
private Session currentSession;
public MyApp() {
currentSession = new Session();
}
public void login() {
//...
if ( studentID != null ) {
if ( password.equals(student.password) ) {
currentSession.setCurrentUserId(studentID);
//...
}
}
//...
}
public void someOtherMethod() {
System.out.println(currentSession.getCurrentUserId());
}
}
答案 1 :(得分:0)
currentStudent = studentID
没有被执行,或者StudentID是你不期望的东西(空字符串?)。启动调试器或只是插入print语句以查看发生的情况:
if (studentID != null) { if (password.equals(student.password)) { currentStudent = studentID; System.out.println ("StudentID is " + studentID); System.out.println ("CurrentID is " + currentStudent); // being paranoid here :-)) studentLoggedOn = true; studentRun(); } }
如果您按照预期验证此显示,则可以进一步挖掘
答案 2 :(得分:0)
根据本网站(#20的问答): http://www.javacertifications.net/javacert/scjp1.5Mock.jsp
Java 1.5