Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.aezart.sous;
- import java.util.HashMap;
- public class Quantity {
- public static enum Type{
- EACH,
- VOLUME,
- MASS
- };
- private static enum LiquidUnits{
- FLOZ(1.0, "fl oz", "fluid ounce", "floz", "fluid ounces"),
- TSP(1/3.0, "tsp", "teaspoon", "teaspoons"),
- TBSP(0.5, "tbsp", "tablespoon", "tablespoons"),
- CUP(8.0, "cup", "cups"),
- GAL(128.0,"gal", "gallon", "gallons");
- double scaleFactor;
- String[] labels;
- LiquidUnits(double scaleFactor, String ... labels){
- this.scaleFactor = scaleFactor;
- this.labels = labels;
- }
- }
- private static enum DryUnits{
- DROZ(1.0, "oz", "ounce", "dry ounce", "ounces", "dry ounces"),
- LB(16.0, "lb", "pound", "pounds");
- double scaleFactor;
- String[] labels;
- DryUnits(double scaleFactor, String ... labels){
- this.scaleFactor = scaleFactor;
- this.labels = labels;
- }
- }
- private static HashMap<String, Double> volCF = new HashMap<>();
- private static HashMap<String, Double> massCF = new HashMap<>();
- private static HashMap<Type, HashMap<String, Double>> scaleMap = new HashMap<>();
- static{
- for (LiquidUnits l :LiquidUnits.values()){
- for (String s: l.labels){
- volCF.put(s, l.scaleFactor);
- }
- }
- for (DryUnits d :DryUnits.values()){
- for (String s: d.labels){
- massCF.put(s, d.scaleFactor);
- }
- }
- scaleMap.put(Type.MASS, massCF);
- scaleMap.put(Type.VOLUME, volCF);
- scaleMap.put(Type.EACH, null);
- }
- private Type type;
- private double quantity = 0.0;
- public Quantity(double quantity,String typeString){
- int foundCount = 0;
- if (volCF.containsKey(typeString)){
- ++foundCount;
- type = Type.VOLUME;
- }
- if (massCF.containsKey(typeString)){
- ++foundCount;
- type = Type.MASS;
- }
- if (foundCount != 1){
- type = Type.EACH;
- }
- this.quantity = quantity;
- }
- public Type getType(){
- return type;
- }
- public double getQuantity(){
- return quantity;
- }
- public void setQuantity(double quantity, String typeString){
- if (scaleMap.get(type) != null){
- if (!isValidUnit(typeString)){
- throw new IllegalArgumentException("Unit " + typeString + " not recognized.");
- }
- this.quantity = quantity * scaleMap.get(type).get(typeString);
- }else{
- this.quantity = quantity;
- }
- }
- public void addQuantity(double quantity, String typeString){
- if (scaleMap.get(type) != null){
- if (!isValidUnit(typeString)){
- throw new IllegalArgumentException("Unit " + typeString + " not recognized.");
- }
- this.quantity += quantity * scaleMap.get(type).get(typeString);
- }else{
- this.quantity += quantity;
- }
- }
- public boolean isValidUnit(String typeString){
- if (scaleMap.get(type) == null){
- return true;
- }
- if (scaleMap.get(type).get(typeString) == null){
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment