我有以下文本文件包含将添加到树形图中的信息。
1 apple
1 orange
3 pear
3 pineapple
4 dragonfruit
我的代码:
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
tMap.put(item, fList);
fList.add(fruit);
System.out.println("Fruits added " + item);
} else {
System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(fList);
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}
理想输出
Number 1:
[apple, orange]
Number 3:
[pear, pineapple]
Number 4:
[dragonfruit]
目前我只能输出这个
Fruits added 1
Number 1:
[apple]
not exist
Number 1:
[apple]
Fruits added 3
Number 3:
[apple, pear]
not exist
Number 3:
[apple, pear]
Fruits added 4
Number 4:
[apple, pear, dragonfruit]
我应该如何显示添加到该数字的水果列表后面的项目?