从.txt文件中读取Double和String不显示所有记录

时间:2022-05-31 19:27:14

I am trying to read the following data from a text file:

我试图从文本文件中读取以下数据:

3.8 Lisa
3.6 John
3.9 Susan
3.7 Kathy
3.4 Jason
3.9 David
3.4 Jack
3.9 Andy
3.8 Fox
3.9 Minnie
2.7 Goofy
3.9 Doc
3.4 Danny

I am then sorting and printing it. However my output is removing duplicate items and I need the full list to display.

然后我正在整理和打印它。但是我的输出是删除重复项目,我需要显示完整列表。

Output:

run:
2.7 Goofy
3.4 Danny
3.6 John
3.7 Kathy
3.8 Fox
3.9 Doc
BUILD SUCCESSFUL (total time: 0 seconds)

Here is my code:

这是我的代码:

package highestgpa;
import java.util.*;
import java.io.*;

public class Main
{

    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("StudentGPA.txt"));
        Map<Double, String> items = new TreeMap<Double, String>();

        String line;
        while (null != (line = br.readLine()))
        {
            String[] line_parts = line.split(" ");
            if (line_parts.length > 1)
            {
                StringBuilder desc = new StringBuilder(line_parts[1]);
                for (int i = 2; i < line_parts.length; i++)
                {
                    desc.append(line_parts[i]);
                }
                items.put(new Double (line_parts[0]), desc.toString());
            }
        }

        for (Double key: items.keySet())
        {
            System.out.println(key + " " + items.get(key));
        }
    }
}

Any help would be greatly appreciated. Thank you!

任何帮助将不胜感激。谢谢!

1 个解决方案

#1


1  

You're using the GPA as a key. When you read in someone with the same GPA and add it to the map, it replaces the previous entry with that same GPA key.

您使用GPA作为密钥。当您阅读具有相同GPA并将其添加到地图的人时,它会使用相同的GPA密钥替换上一个条目。

Instead, try using the name as the key.

相反,请尝试使用名称作为键。

Map<String, Double> items = new TreeMap<String, Double>();

...

items.put( desc.toString(),new Double (line_parts[0]));

...

for (String key: items.keySet())
{
  System.out.println(key + " " + items.get(key));
}

#1


1  

You're using the GPA as a key. When you read in someone with the same GPA and add it to the map, it replaces the previous entry with that same GPA key.

您使用GPA作为密钥。当您阅读具有相同GPA并将其添加到地图的人时,它会使用相同的GPA密钥替换上一个条目。

Instead, try using the name as the key.

相反,请尝试使用名称作为键。

Map<String, Double> items = new TreeMap<String, Double>();

...

items.put( desc.toString(),new Double (line_parts[0]));

...

for (String key: items.keySet())
{
  System.out.println(key + " " + items.get(key));
}