【问题标题】:wrong output of this Dictionary [duplicate]这个字典的错误输出[重复]
【发布时间】:2017-03-07 05:54:34
【问题描述】:

我不断收到此代码的错误输出。当我搜索密钥时,它总是给我 txt 文件的最后一个值。 例如: 这是我的文本文件...

 Sam,123 Main Line,555-0469,123-45-6789,2423.07
 Carla,456 Off Line,555-0101,987-65-4321,1246.15
 Woody,789 Off Rocker,555-0000,010-20-3040,1169.23
 Diane,678 Fifth Ave,555-0690,958-47-3625,10.55
 Norm,987 Suds Blvd.,555-8374,456-78-9000,11.2
 Cliff,321 Duds Lane,555-7282,621-12-1234,12.0
 Tom,2631 Main Blv,423-1155,524-332-6654,10.0
 Kristen,443 Norfolk str,765-9457,010-332-1111,20.0

当我尝试搜索例如:# 621-12-1234

它应该给我 Cliff 的详细信息.. 但相反,它给了我 Kristen 信息。而且,它适用于我搜索的任何数字。

谢谢!

   static Map<String,StaffMember>dictionary1=new HashMap<>();
    static Map<String,StaffMember>dictionary2=new HashMap<>();
    public static void main(String[] args) throws Exception{
        addThemAll();
        searchFor();
    }
    public static void addThemAll() throws Exception
    {
        FileReader file = new FileReader("employee.txt");
        BufferedReader br = new BufferedReader(file);
        StaffMember staff = new StaffMember();
        String line = null;
        while ((line = br.readLine()) != null)
        {
            String[] lineSplit = line.split(",");
            Double rate1=Double.parseDouble(lineSplit[4]);
            staff.SetStaffMember(lineSplit[0], lineSplit[1], lineSplit[2], lineSplit[3], rate1);
            dictionary1.put(lineSplit[3], staff);
            dictionary2.put(lineSplit[0], staff);
        }//end of while loop
    }//end of addThemALL Class

    public static void searchFor()
    {
        Scanner scan= new Scanner(System.in);
        System.out.println("Enter SSN you want to search");
        String SSN=scan.nextLine();
        StaffMember staff1=dictionary1.get(SSN);
        if(dictionary1.containsKey(SSN))
        System.out.println(dictionary1.get(SSN));
    }


}

【问题讨论】:

  • 把你的文本文件也放上来。
  • 你为什么在打电话给containsKey之前拿到钥匙?

标签: java


【解决方案1】:

您只将一个对象放入地图中。

    StaffMember staff = new StaffMember();
    String line = null;
    while ((line = br.readLine()) != null)
    {

你需要很多对象

    String line = null;
    while ((line = br.readLine()) != null)
    {
        StaffMember staff = new StaffMember(); // Move into loop 

【讨论】:

  • 谢谢 cricket_007!做到了……
  • 我做到了,希望它能奏效!
猜你喜欢
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 2015-09-13
  • 2014-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多