2016-01-29 2 views
1

Итак, я хочу вызвать список наборов хэш-карт из основного класса и перечислить их в консоли. Я пытаюсь показать набор ключей перед каждой печатью:Попытка показать список ключей 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; 
} 
+6

В чем ваш вопрос точно? –

ответ

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); 
} 
Смежные вопросы