模拟注册与登录

原创
2016/10/22 13:52
阅读数 76
import java.util.*;

class User
{
	int id;
	String password;
	public User(int id, String password) {
		this.id = id;
		this.password = password;
	}
	public int getId()
	{
		return id;
	}
	public void setId(int id)
	{
		this.id = id;
	}
	public String getPassword()
	{
		return password;
	}
	public void setPassword(String password)
	{
		this.password = password;
	}
	public boolean equals(Object obj)
	{
		User user = (User)obj;
		return this.id==user.id;
	}
	public String toString()
	{
		return "帐号: "+this.id+"  密码: "+this.password;
	}
}

public class Login {
	static Scanner scanner = new Scanner(System.in);
	static Collection users = new ArrayList();
	public static void main(String[] args) {
		while(true)
		{
			System.out.println("s:sign up     l:login");
			String option = scanner.next();
			if("s".equalsIgnoreCase(option))
			{
				System.out.println("开始注册.");
				reg();
			}
			else if("l".equalsIgnoreCase(option))
			{
				System.out.println("开始登录.");
				boolean flag = false;
				while(!login()){}
			}
			else
			{
				System.out.println("选择有误!");
			}
		}
	}
	
	public static void reg()
	{
		User user = null;
		while(true)
		{
			System.out.println("输入想用的用户名(纯数字):");
			int id = scanner.nextInt();
			user = new User(id, null);
			if(users.contains(user))
			{
				System.out.println("已存在的用户名!重新输入");
			}
			else
			{
				break;
			}
		}
		System.out.println("输入密码:");
		String password = scanner.next();
		user.setPassword(password);
		users.add(user);
		System.out.println("注册成功!");
		System.out.println("刚注册的信息为: "+ users);
	}
	
	public static boolean login()
	{
		//boolean flag = false;
		System.out.println("输入用户名:");
		int id = scanner.nextInt();
		System.out.println("输入密码:");
		String password = scanner.next();
		Iterator interator = users.iterator();
		while(interator.hasNext())
		{
			User user = (User)interator.next();
			if(user.id==id&&user.password.equals(password))
			{
				System.out.println("登录成功!");
				//flag = true;
				return true;
			}
		}
		System.out.println("用户名错误或者密码错误!");
		//flag = false;
		return false;
	}
}

运行结果:

s:sign up     l:login
s
开始注册.
输入想用的用户名(纯数字):
120
输入密码:
zx
注册成功!
刚注册的信息为: [帐号: 120  密码: zx]
s:sign up     l:login
l
开始登录.
输入用户名:
120
输入密码:
zx
登录成功!
s:sign up     l:login
 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部