import java.util.Scanner; public class Login { private static String username = "张三"; private static String password = "123456"; public static void main(String[] args) throws ToomanyErrorsException, NamePasswordMismatchException { Scanner scanner = new Scanner(System.in); int count = 0; System.out.println("请输入用户名: "); String username = scanner.next(); while (true) { System.out.println("请输入密码: "); String password = scanner.next(); if ("登录成功".equals(login(username, password))) { System.out.println("登录成功"); break; } count++; if (count==3){ throw new ToomanyErrorsException("密码输入次数已达上限!!!"); } } } public static String login(String username, String password) throws NamePasswordMismatchException { if (!Login.username.equals(username)) { System.out.println("该用户名尚未注册,请核对后输入"); return "用户名有误"; } else { if (!Login.password.equals(password)) { try { throw new NamePasswordMismatchException("密码输入有误"); } catch (Exception e) { e.printStackTrace(); } } else { return "登录成功"; } return "密码有误"; } } }代码中缺失的补充两个自定义异常类,并成功运行程序
时间: 2024-01-02 08:04:18 浏览: 15
以下是补充的两个自定义异常类的代码,分别为ToomanyErrorsException和NamePasswordMismatchException:
ToomanyErrorsException.java
```
public class ToomanyErrorsException extends Exception {
public ToomanyErrorsException(String message) {
super(message);
}
}
```
NamePasswordMismatchException.java
```
public class NamePasswordMismatchException extends Exception {
public NamePasswordMismatchException(String message) {
super(message);
}
}
```
在Login类中的login方法中,当用户名或密码错误时,分别抛出了自定义的NamePasswordMismatchException异常。当错误次数超过3次时,抛出了自定义的ToomanyErrorsException异常。在main方法中,对这两个异常进行了处理。
运行程序时,输入正确的用户名和密码即可成功登录。如果输入错误的用户名或密码,则会抛出NamePasswordMismatchException异常;如果连续3次输入错误的密码,将会抛出ToomanyErrorsException异常。