Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Henrik Christensen
Python Web Development Techdegree Student 38,322 PointsWhy is it being printed in the wrong order?
I'm having a problem with my output being printed in the wrong order :-/
When I run the code I get this output in the console:
new timer - Set and run a new timer
start - Start timer (45 minutes)
quit - Exit the program
but I was actually expecting:
start - Start timer (45 minutes)
new timer - Set and run a new timer
quit - Exit the program
my code
private BufferedReader reader;
private Map<String, String> menu;
private Timer timer;
public TimeForBreak() {
reader = new BufferedReader(new InputStreamReader(System.in));
menu = new HashMap<String, String>();
menu.put("start", "Start timer (45 minutes)");
menu.put("new timer", "Set and run a new timer");
menu.put("quit", "Exit the program");
}
private String promptAction() throws IOException {
for (Map.Entry<String, String> option : menu.entrySet()) {
System.out.printf("%s - %s%n",
option.getKey(),
option.getValue());
}
System.out.print("What do you want to do? ");
String choice = reader.readLine();
return choice.trim().toLowerCase();
}
1 Answer
andren
28,558 PointsThat happens because HashMap is not ordered, the documentation for the class explicitly states:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Which means that you should not use HashMap if the order of the keys is of any importance to you.
If you want a map that is ordered based on insertion then you should use the LinkedHashMap class instead.
Henrik Christensen
Python Web Development Techdegree Student 38,322 PointsHenrik Christensen
Python Web Development Techdegree Student 38,322 PointsVoila, that fixed it!
Thank you very much :-D