Write a Java program to convert Roman number to an integer number


This Java program converts a given Roman numeral to its corresponding integer value. Here's how it works:

  • The program initializes a String variable str with a Roman numeral.
  • The program calculates the length of the str variable and adds a space to the end of it to avoid IndexOutOfBoundsException when checking for the next character.
  • The program initializes an integer variable res to 0, which will hold the final integer value of the Roman numeral.
  • The program uses a for loop to iterate through each character of the str variable.
  • Inside the loop, the program uses a series of if-else statements to check the current character and the next character (if any) and add the corresponding integer value to res.
  • For example, if the current character is 'C' and the next character is 'M', the program adds 900 to res and skips the next character (by incrementing the loop variable).
  • The program then prints the original Roman numeral and its corresponding integer value using the System.out.println method.

Source Code

public class Roman_Number
{
	public static void main(String[] args)
	{ 
		String str = "X";
		int len = str.length();
		str = str + " ";
		int res = 0;
		for (int i = 0; i < len; i++)
		{
			char ch   = str.charAt(i);
			char next_char = str.charAt(i+1);
 
			if (ch == 'M')
			{
				res += 1000;
			}
			else if (ch == 'C')
			{
				if (next_char == 'M') {
					res += 900;
					i++;
				} else if (next_char == 'D') {
					res += 400;
					i++;
				} else {
					res += 100;
				}
			}
			else if (ch == 'D')
			{
				res += 500;
			}
			else if (ch == 'X')
			{
				if (next_char == 'C') {
					res += 90;
					i++;
				} else if (next_char == 'L') {
					res += 40;
					i++;
				} else {
					res += 10;
				}
			}
			else if (ch == 'L')
			{
				res += 50;
			}
			else if (ch == 'I')
			{
				if (next_char == 'X') {
					res += 9;
					i++;
				} else if (next_char == 'V') {
					res += 4;
					i++;
				} else {
					res++;
				}
			}
			else
			{ 
				// if (ch == 'V')
				res += 5;
			}
		}
		System.out.println("Roman Number : "+str);
		System.out.println("Integer Number : "+res);
	}
}

Output

Roman Number : X
Integer Number : 10

Example Programs