所以我遇到了一个不寻常的问题,代码正在使用方法 getCurrentUser()
检测当前用户,但是当我稍后使用它来检查哪个用户借了书时,它返回 null。
我还尝试将borrowBook方法的第3行更改为currentUser变量,并尝试通过usernameTxtField.getText()获取信息
public class Controller {
private Book HFJ = new Book("HFJ", "SI & BA","5678",3, 1);
@FXML
private void attemptLogin(ActionEvent event) throws IOException {
String usernameInput = usernameTxtField.getText();
String passwordInput = passwordTxtField.getText();
boolean loginSuccessful = false;
switch (usernameInput.toLowerCase()) {
case "user1":
if (passwordInput.equals("Password1")) {
System.out.println("Login Successful");
informationLabel.setText("Login Successful");
loginSuccessful = true;
currentUser = usernameInput.toLowerCase();
}
break;
case "user2":
if (passwordInput.equals("Password2")) {
System.out.println("Login Successful");
informationLabel.setText("Login Successful");
loginSuccessful = true;
currentUser = usernameInput.toLowerCase();
}
break;
case "user3":
if (passwordInput.equals("Password3")) {
System.out.println("Login Successful");
informationLabel.setText("Login Successful");
loginSuccessful = true;
currentUser = usernameInput.toLowerCase();
}
break;
case "user4":
if (passwordInput.equals("Password4")) {
System.out.println("Login Successful");
informationLabel.setText("Login Successful");
loginSuccessful = true;
currentUser = usernameInput.toLowerCase();
}
break;
default:
System.out.println("Incorrect username or Password");
informationLabel.setText("Incorrect username or Password");
break;
}
if (loginSuccessful == true) {
Parent home = FXMLLoader.load(getClass().getResource("home.fxml"));
Scene home_scene = new Scene(home);
Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
primaryStage.setScene(home_scene);
primaryStage.show();
currentUser = usernameInput.toLowerCase();
System.out.println(getCurrentUser());
homeLoginInfoLabel.setText("Login Successful");
}
}
@FXML private Label HFJQuantity = new Label();
@FXML private Button HFJBorrowBtn = new Button();
@FXML
private void borrowBook(ActionEvent event) throws IOException{
if(HFJ.getQuantity()>=1){
HFJ.setQuantity(HFJ.getQuantity() -1);
System.out.println("Book Borrowed By: " + getCurrentUser());//CONSOLE PRINT
HFJQuantity.setText("" + HFJ.getQuantity());
Parent borrowSuccessful = FXMLLoader.load(getClass().getResource("borrowSuccess.fxml"));
Scene success_scene = new Scene(borrowSuccessful);
Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
primaryStage.setScene(success_scene);
primaryStage.show();
}else{
System.out.println("Not enough books");
HFJBorrowBtn.setDisable(true);
}
}
private String getCurrentUser() {
return currentUser;
}
当我运行代码并登录时,控制台打印的内容是:
Login Successful
user1
Book Borrowed By: null
为什么它无法识别当前用户?任何帮助都会很棒
最佳答案
我认为您遇到的问题是范围问题。我在这个类中看不到您在 switch 语句或 if/else 之外声明了 currentUser 。尝试使用其他类变量在顶部初始化 currentUser。
关于java - Getter正确返回,然后变为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42964628/