Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This program uses a HashMap to associate a race distance in kilometers with a ru

ID: 3702743 • Letter: T

Question

This program uses a HashMap to associate a race distance in kilometers with a runner's race time. If a race distance does not exist, the program prints "null". Modify the program to use the containsKey() method to check if the runner has run a race of the specified distance, and display a message of "No race of the specified distance exists."

import java.util.HashMap;
import java.util.Scanner;

public class RunDistTimeMap {
public static void main (String[] args) {
HashMap<Integer, Double> raceTimes = new HashMap<Integer, Double>();
Scanner scnr = new Scanner(System.in);
int userDistKm;
  
raceTimes.put(5, 23.14);
raceTimes.put(15, 78.5);
raceTimes.put(25, 120.75);
  
System.out.println("Enter race distance in km (0 to exit): ");
userDistKm = scnr.nextInt();

while(userDistKm != 0) {

System.out.print("Best time for " + userDistKm + " km race is: ");
System.out.print(raceTimes.get(userDistKm));
System.out.println(" minutes.");
System.out.println();

System.out.println("Enter race distance in km (0 to exit): ");
userDistKm = scnr.nextInt();
}   
}
}

Explanation / Answer

The code is

import java.util.HashMap;
import java.util.Scanner;

public class RunDistTimeMap {
public static void main (String[] args) {
HashMap<Integer, Double> raceTimes = new HashMap<Integer, Double>();
Scanner scnr = new Scanner(System.in);
int userDistKm;
  
raceTimes.put(5, 23.14);
raceTimes.put(15, 78.5);
raceTimes.put(25, 120.75);
  
System.out.println("Enter race distance in km (0 to exit): ");
userDistKm = scnr.nextInt();

while(userDistKm != 0) {

if(raceTimes.containsKey(userDistKm)){
System.out.print("Best time for " + userDistKm + " km race is: ");
System.out.print(raceTimes.get(userDistKm));
System.out.println(" minutes.");
System.out.println();
}
else
{System.out.println( "No race of the specified distance exists.");
System.out.println();
}
System.out.println("Enter race distance in km (0 to exit): ");
userDistKm = scnr.nextInt();
}   
}
}

The output is

Enter race distance in km (0 to exit): 5
Best time for 5 km race is: 23.14 minutes.

Enter race distance in km (0 to exit): 15
Best time for 15 km race is: 78.5 minutes.

Enter race distance in km (0 to exit): 50
No race of the specified distance exists.

Enter race distance in km (0 to exit): 0

Do give a thumbs up.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote