简体   繁体   中英

Convert Roman Numerals into numerals using java

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: 
    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));
        }
        
    }

You are starting with i=0 in the loop and then you are checking what the value is for s at index (i-1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM