2

我有一个简单的例子来检查用户使用 MVC 模型的登录..

登录型号:

public class LoginModel {
private String username;
private String password;

public LoginModel()
{        
}
/**
 * @return the username
 */
public String getUsername() {
    return username;
}
/**
 * @param username the username to set
 */
public void setUsername(String username) {
    this.username = username;
}
/**
 * @return the password
 */
public String getPassword() {
    return password;
}
/**
 * @param password the password to set
 */
public void setPassword(String password) {
    this.password = password;
}

}

登录视图:

public class LoginView {
LoginModel user;

//Ham khoi tao cho LoginView
public LoginView(LoginModel user)
{
  this.user=user;
}

public void showMessage(String msg)
{
  System.out.println(msg);
}

public void getUserInfo()
{
try
{

    DataInputStream input=new DataInputStream(System.in);
    System.out.println("Username:");
    user.setUsername(input.readUTF());
    System.out.println("Password:");
    user.setPassword(input.readUTF());
    input.close();
}
catch(IOException e)
{
    System.out.println(e);
}

} }

登录控制:

public class LoginControl {
LoginModel user;
LoginView view;

public LoginControl(LoginModel user,LoginView view)
{
    this.user=user;
    this.view=view;
    while(true)
    {
    view.getUserInfo();
    if(checkLogin())
    {
        view.showMessage("Success");
    }
    else
    {
        view.showMessage("Wrong username or password");
    }
    }
}

private boolean checkLogin()
{
    if((user.getUsername().equals("sa"))&&(user.getPassword().equals("sa")))
    {
        return true;
    }
    return false;
}

}

登录主:

public class LoginMVC {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    LoginModel user=new LoginModel();
    LoginView view=new LoginView(user);
    LoginControl control=new LoginControl(user, view);
}

}

但是当我运行主类时,只有用户名:并输入用户并停止..我不知道错误在哪里。你能帮助我吗。

4

1 回答 1

0

我不确定为什么DataInputStream不起作用,我建议使用Scanner从方法中的控制台获取输入getUserInfo

  Scanner scanner = new Scanner(System.in);
  System.out.println("Username:");
  user.setUsername(scanner.nextLine());
  System.out.println("Password:");
  user.setPassword(scanner.nextLine());
  scanner.close();
于 2012-12-14T06:48:18.473 回答