I am working on a TreeMap with an iterator that reads a text file with 20 name and hexadecimal values for example RED; FF0000. First in the main I made an Iterator but I am not sure why its not reading all 20 and displaying. Also trying to sort them in increasing value when I display them to the console.
Console Display:
`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`
Code:
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));
}
}
See your code here:
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());
^^^^^^^^^^^^^^^^^^
}
See that you are calling next method twice.
So you are advancing the cursor of iterator by calling next method on iterator two times and hence you see n/2 map elements in your output. You could just print map entry instead like:
System.out.println(entry);