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("輸入有誤,請你重新選擇!!!!");
}
}
}
}
解決了
public int compareTo(User o) {
int m=this.userName.compareTo(o.userName);
int n=this.passWord.compareTo(o.passWord);
if(m==0&n==0)
{
return 0;
}
return -1;
}