qx7Adai11
2016-06-15 11:57
采纳率: 57.1%
浏览 1.2k
已采纳

Java多态:用 Set的子类 模拟登陆注册过程

User.java

package com.qf.homework;

public class User implements Comparable{
private String userName;
private String passWord;
public User(String userName, String passWord) {
super();
this.userName = userName;
this.passWord = passWord;
}
public User() {
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public int hashCode() {
return 10;
}
@Override
public boolean equals(Object obj) {
User u=(User)obj;
return this.userName.equals(u.userName)&&this.passWord.equals(u.passWord);
}

@Override
public String toString() {
    return "User [passWord=" + passWord + ", userName=" + userName + "]";
}
@Override
public int compareTo(User o) {
    if(this.userName.equals(o.userName)&&(this.passWord==o.passWord)){
        System.out.println("比较");
        return 0;

    }else
    {
        System.out.println("0.0");
        return 1;
    }


}

}

Test.java
package com.qf.homework;

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Set set=new TreeSet();
Set setR=new TreeSet();

while(true){
System.out.println("请你选择你需要的功能: 1.登陆          2.注册");
int c1=in.nextInt();//接收选择的数字
if(c1==1){

    System.out.println("请输入你的用户名:");
    String loginUser = in.next();//接收用户名
    System.out.println("请输入你的密码:");
    String loginpwd=in.next();//接收密码
    User user=new User(loginUser,loginpwd);
    System.out.println(setR.contains(loginUser));
    if(setR.contains(loginUser))
    {
        System.out.println(set.contains(user));
        System.out.println(set);
       if(set.contains(user))
       {
           System.out.println("登陆成功!");//判断用户是否可以登陆
       }
       else
       {
           System.out.println("登陆失败!");
       }
    }
    else
    {
        System.out.println("登陆失败!");
    }
}else if(c1==2)
{
    User user2=new User();
    System.out.println("请输入你想要注册的用户名");
    String  rUser=in.next();
    if(setR.add(rUser))
    {
        System.out.println("请输入你想要注册的密码");
        String rPwd=in.next();
        user2.setUserName(rUser);
        user2.setPassWord(rPwd);
        set.add(user2);
        System.out.println("注册成功");
        System.out.println(set);
    }
    else
    {
        System.out.println("注册失败 不能有相同的用户名!!!");
    }



}else
{
    System.out.println("输入有误,请你重新选择!!!!");
}
}

}
}

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题