所以,我想从主类调用hashmap键集列表并在控制台中列出它们。我想在每次打印前显示键集:
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);
}
**
以下是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;
}
答案 0 :(得分:1)
修复Length
课程:
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());
}
}
更新main
方法:
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);
}