实现登录验证: 输入用户名 和密码,判断是否 为“root”和“012” 如果用户名输入错误,生成错误信息为“用户名不存在”的异常对象;如果用户名正确,密码输入错误,生成错误信息为“密码不正确”的异

该代码示例展示了如何创建并使用自定义异常类进行登录验证。程序中定义了`user`、`password`和`XXX`三个异常类,分别对应用户名不存在、密码错误和用户名密码均错误的情况。在`main`方法中,通过`Scanner`获取用户输入的用户名和密码,并尝试调用`judge`方法进行登录判断。如果发生异常,根据捕获的异常类型输出相应的错误信息。
摘要由CSDN通过智能技术生成

package oj512;

import java.util.Scanner;

public class diy2 {
//关键在于创建三个自定义异常类 返回三种情况!!!
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cc=new Scanner(System.in);

	String name=cc.next();
	String code=cc.next();
	code1 a=new code1();
	
		try {
			a.judge(name, code);
		} catch (user e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println("登录失败,原因是:用户名不存在");
		} catch (password e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println("登录失败,原因是:密码不正确");
		}
		catch (XXX e) {
		// TODO Auto-generated catch block
		//e.printStackTrace();
		System.out.println("用户名密码都不正确");
	}
	 
}

}
class code1{
public String name;
public String code;
public code1(String name,String code)
{
super();
this.name=name;
this.code=code;
}
public code1() {
// TODO Auto-generated constructor stub
}
public void judge(String name,String code)throws XXX, user,password
{
if(name.equals(“root”)&&code.equals(“012”))
System.out.println(“登陆成功!”);
if(!name.equals(“root”))
throw new user();
if(!code.equals(“012”))
throw new password();
else
throw new XXX();
}
}class XXX extends Exception{
public XXX(){
}
public XXX(String message) {
super(message);
}
}
class user extends Exception{
public user(){
}
public user(String message) {
super(message);
}
}
class password extends Exception{
public password(){
}
public password(String message) {
super(message);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值