Reputation: 11
So, I want to call the hashmap keyset list from the main class and list them in console. I am trying to show the keyset before each printing:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// The keyset can be set here to show the alternatives to convert to the user
System.out.println("What length you want to confert from");
String to = input.nextLine();
System.out.println("What length you want to confert to");
String from = input.nextLine();
System.out.println("Input length");
double value = input.nextDouble();
int result = (int)Length.convert(value, from, to);
System.out.println((int )value + from + " = " + result + to);
}
**
Here is the second method in Length
for converting the length:
**
public static double convert(double value, String from, String to){
HashMap<String, Double> table= new HashMap<>();
table.put("mm", 0.001);
table.put("cm", 0.01);
table.put("dm", 0.1);
table.put("m", 1.0);
table.put("hm", 100.0);
table.put("km", 1000.0);
table.put("ft", 0.3034);
table.put("yd", 0.9144);
table.put("mi", 1609.34);
double from_value = table.get(from);
double to_value = table.get(to);
double result = from_value / to_value * value;
return result;
}
Upvotes: 1
Views: 82
Reputation: 397
Fix the Length
class :
class Length {
//Declare the map as class variable
static Map<String, Double> table = new HashMap<>();
//Initialize the map
static {
table.put("mm", 0.001);
table.put("cm", 0.01);
table.put("dm", 0.1);
table.put("m", 1.0);
table.put("hm", 100.0);
table.put("km", 1000.0);
table.put("ft", 0.3034);
table.put("yd", 0.9144);
table.put("mi", 1609.34);
}
public static double convert(double value, String from, String to) {
double from_value = table.get(from);
double to_value = table.get(to);
double result = from_value / to_value * value;
return result;
}
//Print the KeySet
public static void printMap() {
System.out.println(table.keySet());
}
}
Update the main
method :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Show Keyset
Length.printMap();
System.out.println("What length you want to confert from");
String to = input.nextLine();
System.out.println("What length you want to confert to");
String from = input.nextLine();
System.out.println("Input length");
double value = input.nextDouble();
int result = (int) Length.convert(value, from, to);
System.out.println((int) value + from + " = " + result + to);
}
Upvotes: 1