通过增加值问题对TreeMap进行排序和显示

时间:2015-03-08 16:34:40

标签: java sorting iterator hex treemap

我正在使用迭代器处理TreeMap,该迭代器读取具有20个名称和十六进制值的文本文件,例如RED; FF0000。首先,我做了一个迭代器,但我不确定为什么它不读全部20并显示。当我将它们显示到控制台时,还尝试对它们进行增值。

控制台显示:

`00008B=Dark Blue
013220=Dark Green
37FDFC=Blue
7f7f00=Dark Yellow
8B0000=Dark Red
B26200=Dark Orange
D3D3D3=Grey
FF0000=Red
FFC0CB=Pink
FFFFCC=Light Yellow`

代码:

public class coloring extends JFrame implements ActionListener {

public static TreeMap<String, String> buttonColors;

// Constructor
public FP(TreeMap<String, String> buttonColors) throws IOException {

    super("Hexidecimal Button Map");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.buttonColors = buttonColors;

    setSize(500, 400);
    setLayout(new FlowLayout());
    ButtonGroup buttonGroup = new ButtonGroup();

    for (Map.Entry<String, String> coloringButtons : buttonColors
            .entrySet()) {

        JRadioButton button = new JRadioButton(coloringButtons.getValue()
                + "  " + coloringButtons.getKey());

        button.setActionCommand(coloringButtons.getKey());
        button.addActionListener(this);

        buttonGroup.add(button);
        add(button);
    }
}

public void actionPerformed(ActionEvent e) {

    String color = e.getActionCommand();
    getContentPane().setBackground(new Color(Integer.parseInt(color, 16)));

}

public static void main(String[] args) throws IOException {

    TreeMap<String, String> buttonColors = new TreeMap<String, String>();

    BufferedReader br = new BufferedReader(new FileReader("Input File.txt"));

    while (true) {
        String str = br.readLine();
        if (str == null)
            break;
        if (str.length() == 0)
            continue;
        String[] st = str.split("; ");
        String colorName = st[0].trim();
        String colorValue = st[1].trim();

        buttonColors.put(colorValue, colorName);
    }

    br.close();

    Set<Map.Entry<String, String>> buttons = buttonColors.entrySet();
    Iterator sortingItr = buttons.iterator();

    while (sortingItr.hasNext()) {

        Map.Entry<String, String> entry = (Map.Entry) sortingItr.next();
        System.out.println(sortingItr.next());

    }

    FP obj = new FP(buttonColors);
    obj.setVisible(true);
    obj.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
}
}

1 个答案:

答案 0 :(得分:1)

在此处查看您的代码:

Set<Map.Entry<String, String>> buttons = buttonColors.entrySet();
Iterator sortingItr = buttons.iterator();
while (sortingItr.hasNext()) {
    Map.Entry<String, String> entry = (Map.Entry) sortingItr.next();
                                                  ^^^^^^^^^^^^^^^^^
    System.out.println(sortingItr.next());
                       ^^^^^^^^^^^^^^^^^^
}

看到您正在调用下一个方法两次。

所以你通过在迭代器上调用next方法两次来推进迭代器的游标,因此你会在输出中看到n / 2个map元素。您可以只打印地图条目,如:

System.out.println(entry);