gpt4 book ai didi

java - 尝试在其他方法中显示 HashMap 键集的列表

转载 作者:行者123 更新时间:2023-11-30 07:38:05 43 4
gpt4 key购买 nike

所以,我想从主类调用 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;
}

最佳答案

修复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);
}

关于java - 尝试在其他方法中显示 HashMap 键集的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35081778/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com