【发布时间】:2017-03-26 22:43:19
【问题描述】:
尽管查看了一些教程,但我最大的问题很可能是没有完全理解 Hashmap 以及如何操作它们。希望你们聪明的灵魂能够为我指明正确的方向。
我正在尝试将 .txt 文件读入哈希图中。文本文件包含 2006 年的流行名称。 inputFile 的每一行都包含一个男孩的名字和一个女孩的名字以及有多少人被命名。例如:1 Jacob 24,797 Emily 21,365 将是文件第 1 行的输入。
我想把男孩的名字放在一个列表中,女孩的名字放在第二个列表中,保持他们当前的位置,这样用户就可以搜索 jacob 并被告知这是当年排名第一的男孩名字,依此类推对于其他名称。以前我只是逐行读取文件并查看文件包含我正在搜索的名称的哪一行。这有效,但它无法判断它是男孩名字还是女孩名字,导致错误,如果我说我正在搜索 Jacob 对女孩的受欢迎程度,它仍然会显示数字 1。我确定 hashmap 会成为解决此问题的最佳方法,但无法真正使其正常工作。
我的代码
public void actionPerformed(ActionEvent e)
{
//Parse Input Fields
String name = inputArea.getText();
if (name.equals(""))
{
JOptionPane.showMessageDialog(null, "A name is required.", "Alert", JOptionPane.WARNING_MESSAGE );
return;
}
String genderSelected = genderList.getSelectedItem().toString();
String yearSelected = yearList.getSelectedItem().toString();
String yearFile = "Babynamesranking"+yearSelected+".txt"; //Opens a different name file depending on year selection
boolean foundName = false;
Map<String, String> map = new HashMap<String,String>(); //Creates Hashmap
try
{
File inputFile = new File(yearFile); //Sets input file to whichever file chosen in GUI
FileReader fileReader = new FileReader(inputFile); //Creates a fileReader to open the inputFile
BufferedReader br = new BufferedReader(fileReader); //Creates a buffered reader to read the fileReader
String line;
int lineNum = 1; //Incremental Variable to determine which line the name is found on
while ((line = br.readLine()) != null)
{
if (line.contains(name))
{
outputArea.setText(""+name+" was a popular name during "+yearSelected+".");
outputArea.append("\nIt is the "+lineNum+" most popular choice for "+genderSelected+" names that year.");
foundName = true;
}
String parts[] = line.split("\t");
map.put(parts[0],parts[1]);
lineNum++;
}
fileReader.close();
}
catch(IOException exception)
{
exception.printStackTrace();
}
String position = map.get(name);
System.out.println(position);
}
示例输入文件:
1 Jacob 24,797 Emily 21,365
2 Michael 22,592 Emma 19,092
3 Joshua 22,269 Madison 18,599
4 Ethan 20,485 Isabella 18,200
5 Matthew 20,285 Ava 16,925
6 Daniel 20,017 Abigail 15,615
7 Andrew 19,686 Olivia 15,474
8 Christopher 19,635 Hannah 14,515
【问题讨论】:
-
总是男孩名后女孩名的情况,还是可以颠倒?
-
总是这样
-
如果(男孩被选中)查看部分[0],否则查看部分[1]。
-
使得 hashmap 包含 {name,popularity} 对。