this is my first Java app. I'm trying to create a map of products (keys) and their prices (values). The documentation says I can't use doubles for money, so I have to use BigDecimal. I'm completely stuck at the moment as to how to use BigDecimal in my methods and the map.
I only have a method to add products to the map and I'm trying to pass in a BigDecimal Price. It won't compile, because it sees a string instead of a BigDecimal, which confuses me, because BigDecimal accepts strings as a parameter (e.g. BigDecimal example = new BigDecimal("2.50") )
I also want to create a method that will add prices to a total, but you can't do that with strings. The documentation on BigDecimal is very confusing and Google isn't very helpful. Could someone please explain BigDecimal and how to use it?
This is my code so far:
Register class:
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
public class Register {
private HashMap<String, BigDecimal> productMap = new HashMap<>();
public void printProductMap() {
for(Map.Entry<String, BigDecimal> entry : productMap.entrySet()) {
String key = entry.getKey();
BigDecimal value = entry.getValue();
System.out.println(key + " " + value);
}
}
public HashMap<String, BigDecimal> addProduct(String product, BigDecimal price) {
BigDecimal productPrice = new BigDecimal(price);
productMap.put(product, productPrice);
return productMap;
}
}
Main class:
public class Main {
public static void main(String[] args) {
Register register = new Register();
register.addProduct("Coffee", "1.25");
register.addProduct("Cappuccino", "1.50");
register.printProductMap();
}
}