Question: Write a program that calculates the price of a part. This part has multiple sub-parts with their own respective cost. Would using a HashMap be the best way to do this?
Here's what I have:
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
import java.text.NumberFormat;
public class RocketStructure {
public static void main(String args[]) {
/*Declare HashMap and Formatter*/
HashMap<String, Double> hmap = new HashMap<String, Double>();
NumberFormat formatter = NumberFormat.getCurrencyInstance();
/*Adding elements to HashMap (Name, Price)*/
hmap.put("Nose Cone", 1233863.45);
hmap.put("Frame", 76495.26);
hmap.put("Pumps", 4679358.25);
hmap.put("Fin", 467945.25);
hmap.put("Nozzle", 46235.72);
/*HashMap Size and Part Information*/
System.out.println("Rocket Structure | Total Parts: " +hmap.size());
System.out.println("----------------------------------");
/*Display content using iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print(mentry.getKey() + " | Cost: ");
System.out.println(formatter.format(mentry.getValue()));
}
/*Calculate total value of all sub parts*/
double sum = 0f;
for (double value : hmap.values()) {
sum += value;
}
System.out.println("----------------------------------");
System.out.println("Total Cost: " +formatter.format(sum));
}
}
Result:
Rocket Structure - Total Parts: 5
Frame | Cost: $76,495.26
Nose Cone | Cost: $1,233,863.45
Pumps | Cost: $4,679,358.25
Nozzle | Cost: $46,235.72
Fin | Cost: $467,945.25
Total Cost: $6,503,897.93