I am always getting index out of Bound exception what is wrong in this code: I am using Hashmap to store the Roman numerals to integer values and trying to retrieve it by using the get method.
package edu.code.leet;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class RomanTo_int {
public static int romanToInt(String s) {
Map<Character, Integer> mp = new HashMap<Character, Integer>();
mp.put('I', 1);
mp.put('V', 5);
mp.put('X', 10);
mp.put('L', 50);
mp.put('C', 100);
mp.put('D', 500);
mp.put('M', 1000);
int result =0;
int i=0;
for(i=0; i<s.length(); i++) {
if(mp.get(s.charAt(i))<mp.get(s.charAt(i-1))){
result += mp.get(s.charAt(i));
}
else{
result = mp.get(s.charAt(i)) - 2*mp.get(s.charAt(i-1));
}
}return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Roman number");
String num = sc.nextLine();
romanToInt(num);
sc.close();
}
}
MY OUTPUT:
Enter a Roman number
X
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: