-3

I am a student, I'm trying to practice hashmaps. I can input roman numerals inside loops and if statements to convert into accurate decimals. i want to enter MDCLXVI.

public static void main(String[] args) {
    String inputstr;
    Integer outputstr ;

     System.out.println("Enter Roman Numneral(s): ");
     Scanner sc = new Scanner(System.in);
     inputstr = sc.nextLine().toUpperCase();

     HashMap<String, Integer> numeral = new HashMap<String, Integer>();

     numeral.put("IV", 4);
     numeral.put("IX", 9);
     numeral.put("XL", 40);
     numeral.put("CD", 400);
     numeral.put("CM", 900);
     numeral.put("C", 100);
     numeral.put("M", 1000);
     numeral.put("I", 1);
     numeral.put("V", 5); 
     numeral.put("X", 10);
     numeral.put("L", 50);
     numeral.put("D", 500);

     outputstr = numeral.get(inputstr);

     System.out.println(inputstr + " =  " + outputstr);
}

My question is: how can I enter more than one key to get desired decimal?

DimaSan
  • 12,264
  • 11
  • 65
  • 75

2 Answers2

0

You won't be able to make one call to the map to get the answer. That's simply not what a map is designed to do.

What you should be doing is thinking about how you learned to read roman numerals. Take the simple example XIV, which you can look up in your map as meaning 10, 1, and 5. Because 10 > 1, you add the 10 to the result (result = 10). Then, as 1 < 5, you subtract 1 from 5 and add it to the result (result = 14).

That should be enough for you to translate this into the code you need.

Joe C
  • 15,324
  • 8
  • 38
  • 50
0

numeral.get will return a value if the key exists in the hashmap else a null. When you call numeral.get(inputstr) for "MDCLXVI" the actual call is numeral.get("MDCLXVI") but "MDCLXVI" doesn't exist in your hash so it returns null, that's why your Hash isn't working.

Instead of doing a direct numeral.get(inputstr), the inputstr needs to be parsed and then each parsed roman character needs to be passed to .get and calculated. Look at: Converting Roman Numerals To Decimal

Community
  • 1
  • 1
Sid
  • 408
  • 4
  • 7