如何打印树状图中的所有值?

2022-09-03 04:49:23

我有一个项目,我正在为我的Java课程工作(显然),我一定错过了关于如何与TreeMaps交互的讲座。我不知道我用这部分做了什么,我没有从谷歌找到很多帮助。

对于程序中的第一种情况,我必须打印树状图的所有值。以下是我获得的代码以及我用它所做的工作。如果A是我的,但它不起作用。任何帮助将不胜感激。

import java.util.Scanner;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.io.File;
import java.io.FileNotFoundException;

public class prog7 {
 public static void main(String args[])
 throws FileNotFoundException
 {
Scanner kb=new Scanner(System.in);

/*here, add code to declare and create a tree map*/
TreeMap treeMap = new TreeMap();

/*here, add code to declare a variable and
 let it be the key set of the map
 */
String key;

//temporary variables
String tempWord;
String tempDef;

//the following code reads data from the file glossary.txt
//and saves the data as entries in the map
Scanner infile=new Scanner(new File("glossary.txt"));

while(infile.hasNext())
{
  tempWord=infile.nextLine();
  tempDef=infile.nextLine();

  /*here, add code to add tempWord and tempDef
   as an entry in the map
   */
  treeMap.put(tempWord, tempDef);

}
infile.close();

while(true)
{
  System.out.println();
  System.out.println();

  //show menu and prompt message
  System.out.println("Please select one of the following actions:");
  System.out.println("q - Quit");
  System.out.println("a - List all words and their definitons");
  System.out.println("b - Enter a word to find its definition");
  System.out.println("c - Add a new entry");
  System.out.println("d - Delete an entry");
  System.out.println("Please enter q, a, b, c or d:");

  String selection=kb.nextLine();  //read user's selection
  if (selection.equals("")) continue; //if selection is "", show menu again

  switch (selection.charAt(0))
  { 
    case 'q':
      System.out.println("\nThank you.");
      return;

      /*write code for the cases 'a','b','c' and 'd'
       so that the program runs as in the sample run
       */

    case 'a':
       for (String treeKey : treeMap.keySet())
          System.out.println(treeKey);


    break;

答案 1

循环访问条目集而不是键集。你得到一套方便和方法。Map.Entry<K, V>getKey()getValue()

也就是说,Java的标准Map实现具有toString()的实现,它可以做您想要的操作。当然,我认为你只会因为重新实现它而得到分数,而不是因为巧妙地避免它......

for (Map.Entry<K, V> entry : myMap.entrySet()) {
     System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue());
}

答案 2

您可以使用 entrySet()。Java中的每个Map都有这种方法。

Map<String, String> tree = new TreeMap<String, String>();
tree.put("param1", "value1");
tree.put("param2", "value2");
for (Entry<String, String> entry : tree.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();

    System.out.printf("%s : %s\n", key, value);
}

推荐