KaiquanMah's picture
for (String city : cityNTemps.keySet())
16b1b2e verified
raw
history blame
2.68 kB
Write the method
String coldestCity(HashMap<String, Double> temps)
which takes as its parameter a hashmap where the keys are city names and the values are temperatures.
Your task is to find and return the name of the city with the lowest temperature.
Example method call:
public static void main(String[] args){
HashMap<String, Double> temps = new HashMap<>();
temps.put("Turku", 0.5);
temps.put("Tampere", -5.25);
temps.put("Helsinki", -2.5);
System.out.println("Coldest city: " + coldestCity(temps));
}
Program outputs:
Coldest city: Tampere
=====================================
import java.util.Random;
import java.util.HashMap;
public class Test{
public static void main(String[] args){
final Random r = new Random();
for (int testi=1; testi<=3; testi++) {
System.out.println("Test " + testi);
String[] kaup = "Turku Helsinki Tampere Rovaniemi Oulu Kajaani Jyväskylä Pori Vaasa".split(" ");
HashMap<String, Double> lt = new HashMap<>();
double[] add = {0, 0.25, 0.5, 0.75};
for (String kaupunki : kaup) {
double l = 25 - r.nextInt(50);
//'add' array of 4 floats are used here
// randomly select 0-3 idx
// then pick up the float value from the 'add' array
// and add to the 'l' temperature
l += add[r.nextInt(4)];
lt.put(kaupunki, l);
}
System.out.println("Temperatures: ");
System.out.println("" + lt);
System.out.println("Coldest city: " + coldestCity(lt));
System.out.println("");
}
}
public static String coldestCity(HashMap<String, Double> cityNTemps) {
String coldest = "";
double coldestTemp = 999;
for (String city : cityNTemps.keySet()) {
if (cityNTemps.get(city) < coldestTemp) {
coldest = city;
coldestTemp = cityNTemps.get(city);
}
}
return coldest;
}
}
Test 1
Temperatures:
{Pori=-8.0, Jyväskylä=14.0, Kajaani=-16.0, Oulu=-1.0, Helsinki=1.0, Rovaniemi=1.0, Turku=20.5, Tampere=0.0, Vaasa=-2.75}
Coldest city: Kajaani
Test 2
Temperatures:
{Pori=-8.25, Jyväskylä=20.5, Kajaani=-21.0, Oulu=8.5, Helsinki=-4.5, Rovaniemi=-1.0, Turku=14.75, Tampere=12.75, Vaasa=1.0}
Coldest city: Kajaani
Test 3
Temperatures:
{Pori=9.75, Jyväskylä=4.5, Kajaani=-11.5, Oulu=-10.25, Helsinki=-12.5, Rovaniemi=20.0, Turku=9.5, Tampere=-8.0, Vaasa=7.75}
Coldest city: Helsinki