日期:2014-05-20 浏览次数:21096 次
import java.io.*;
class PasswordException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
private int i = 0;
public PasswordException(final int i) {
super();
this.i = i;
}
public String getMessage() {
if (i == 0) {
return "没有这个用户";
} else if (i == 1) {
return "密码错误,请重新输入";
}
return " ";
}
}
public class UserLogin {
private String userName = "";
private String password = "";
public void login() {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("请输入用户名:");
try {
userName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("请输入密码:");
try {
password = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
public void checkPassword() throws PasswordException {
if (!userName.equals("administrator")) {
throw new PasswordException(0);
} else if (!password.equals("admin")) {
throw new PasswordException(1);
}else{
System.out.println("密码已验证正确");
}
}
public static void main(String[] args) {
UserLogin app = new UserLogin();
app.login();
try {
app.checkPassword();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
------解决方案--------------------
没错啊。
/** * */ package cn.luochengor.csdn; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @Author luochengor * @Date Nov 26, 2011 * @Email luochengor@foxmail.com */ @SuppressWarnings("serial") class PasswordException extends Exception { private int i = 0; public PasswordException(int i) { super(); this.i = i; } public String getMessage() { if (i == 0) { return "没有这个用户"; } else if (i == 1) { return "密码错误,请重新输入"; } return " "; } } public class UserLogin { private String userName = ""; private String password = ""; public void login() { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println("请输入用户名:"); try { userName = br.readLine(); } catch (IOException e) { System.out.println("输入被中断"); } System.out.println("请输入密码:"); try { password = br.readLine(); } catch (IOException e) { System.out.println("输入被中断"); } } public void checkPassword() throws PasswordException { if (!userName.equals("administrator")) { throw (new PasswordException(0)); } else if (!password.equals("admin")) { throw (new PasswordException(1)); } } public static void main(String[] args) { UserLogin app = new UserLogin(); app.login(); try { app.checkPassword(); System.out.println("密码已验证正确"); } catch (Exception e) { System.out.println(e.getMessage()); } } }