模擬註冊與登入
阿新 • • 發佈:2018-11-02
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