注册 登录
编程论坛 JAVA论坛

h.contains(id) 怎么没有用啊 哪位大神帮忙看看

zhouwei025 发布于 2015-09-23 23:44, 363 次点击
package work1;
import java.util.*;
public class TestEmployee {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        HashSet h=new HashSet();
        do {
            System.out.println("请选择:1.添加员工  2.显示信息  3.按姓名查询");
            int select = sc.nextInt();
            if (select == 1) {
                System.out.println("请输入姓名:");
                String name = sc.next();
                System.out.println("请输入工资金额:");
                double salary = sc.nextDouble();
                String id;
                do {
                    System.out.println("请输入员工号:");
                    id = sc.next();
                    if(h.contains(id)){   //******************
                        break;
                    } else {
                        System.out.println("此员工号已存在,请重新输入!");
                    }
                } while (true);
                Employee emp = new Employee(name, id, salary);
                h.add(emp);
            } else if (select == 2) {
                Iterator it=h.iterator();
                while(it.hasNext()){
                    System.out.println(it.next().toString());
                }
            } else if (select == 3) {
               
            } else if (select == 0) {
                break;
            } else {

            }
        } while (true);
        
    }
}
//*******************************************************
public class Employee {
    private String name;
    private String id;
    private double salary;
    public Employee(String name, String id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "姓名:" + name+"  工号:" + id  + "  工资:" + salary;
    }   
}
2 回复
#2
calix2015-09-24 08:40
h里面放的是Employee对象,不是String,类型不匹配
h.contains(id)这样每次都是false

if(h.contains(id)){   //******************
    break;
} else {
    System.out.println("此员工号已存在,请重新输入!");
}
还有这块写反了,在包含的时候应该打印提示信息,否则跳出
#3
zhouwei0252015-09-24 20:24
恩恩  谢谢
1