Using hashmaps, breaking loops and user input in java
I'm fairly new to programming in general and need some help.
I am using the Java.util.TimeZone to retrieve the IDs (city names) and their time zones. I am using a hashmap to implement this. I have put the city names and the time zones in the map and I am now trying to ask the user to enter a city they wish to get the time zone of.
However, in my loop I have a validation check to make sure the city name is in the hashmap. Not only is it not working but the loop also does not break. It correctly puts out the time it is currently but not the correct timezone for the city (I have typed various city names and all have about the same timez开发者_如何学编程one). After printing out the local time it is in the city the user can choose to end the program by "saying yes".
If the user enters yes then the loop should break and the the program should end. If they enter anything else it should continue.
Could someone please help me fix this! Here is my code.
import java.util.*;
import java.util.TimeZone;
import java.util.Date;
import java.text.DateFormat;
import java.util.HashMap;
class Maps {
public static void main(String[] args) {
String[] Zone = TimeZone.getAvailableIDs();
int i = 0;
for (i = 0; i < Zone.length; i++) {
String zone1 = Zone[i].replaceAll("_", " ");
if (zone1.indexOf('/') != -1) {
zone1 = zone1.substring(zone1.indexOf('/') + 1);
}
TimeZone tz = TimeZone.getTimeZone(zone1);
HashMap hm = new HashMap();
HashMap<String, Integer> map = new HashMap<String, Integer>();
hm.put(zone1, tz);
// System.out.println(hm);
while (hm != null) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("City?");
String city = input.nextLine();
boolean CityExist = hm.containsKey(city);
if (CityExist == true) {
System.out
.println("I can not find a match to the city, sorry. ");
break;
}
TimeZone tz2 = TimeZone.getTimeZone(city);
DateFormat timeFormatter = DateFormat.getTimeInstance();
Date now = new Date();
System.out.println("Here: " + timeFormatter.format(now));
System.out.print("Local Time: ");
timeFormatter.setTimeZone(tz2);
System.out.println(timeFormatter.format(now));
System.out
.println("If you would like to quit please enter yes: ");
String user = input.nextLine();
if (user.equals("yes") || user.equals("Yes")) {
break;
}
}
}
}
}
Looks like you have the logic inverted: if CityExist
then there was no match?
Please format your code next time.
Doing this, you will see that your first for
loop is not closed and you are doing while
loop still inside your for
loop.
Solution, put the close bracket }
before while
loop.
精彩评论