gpt4 book ai didi

java - 需要 HashMap 帮助

转载 作者:行者123 更新时间:2023-12-02 03:55:14 24 4
gpt4 key购买 nike

Program 1: You are a runner, and you are in training for a race. You'd like to keep track of all of your times for your training runs. You only like to run around lakes. Here's some example data,

Calhoun, 45.15
Calhoun, 43.32
Harriet, 49.34
Harriet, 44.43
Harriet, 46.22
Como, 32.11
Como, 28.14

Please write a program which enables you to enter the names of lakes and times, and store it all of this data in data structure(s). Don't store it in individual variables. Your program should still work if you started running around another lake too (e.g. Cedar or Phalen).

Your program should be able to analyze the data that you have stored, and print your fastest time for each lake you ran around. So, for this data, your program will display

Calhoun, 43.32
Harriet, 44.43
Como, 32.11

Your program should use input validation.

You should use methods to organize your program.

这就是我试图通过使用 HashMap 来实现的。但似乎不起作用。

import java.util.*;

public class Main {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Creating a HaspMap as String for Key and Double for value
HashMap<String, Double> map = new HashMap<String, Double>();
String lakeName;//Variable to store lake name
double time;//Variable to store time




while (true){
System.out.println("What is the lake name: ");
lakeName = input.next();
System.out.println("How many minutes did you run: ");
time = input.nextDouble();
map.put(lakeName, time);//Addding Lake Name to and time to theHaspMap


if (lakeName.equalsIgnoreCase("A") || time ==1)//A condition to exit the loop
{
break;


}

}
System.out.println();
}
}

最佳答案

使用 HashMap<String, Double>允许您为每个湖泊仅存储一个结果。如果将其更改为 HashMap<String, List<Double>> ,您将能够存储每个湖泊的多个结果,并找到给定湖泊的最快结果。

而不是

map.put(lakeName, time);

你会得到类似的东西:

List<Double> times = map.get(lakeName);
if (times == null) {
times = new ArrayList<Double>();
map.put(lakeName,times);
}
times.add(time);

关于java - 需要 HashMap 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35552435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com