Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Math Exercises: Convert Roman number to an integer number

Java Math Exercises: Exercise-7 with Solution

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

Sample Solution:

Java Code:

public class Example7 {
   public static void main(String[] args) {
	String str = "DCCVII";
	int len = str.length();

        str = str + " ";
        int result = 0;
        for (int i = 0; i < len; i++) {
            char ch   = str.charAt(i);
            char next_char = str.charAt(i+1);
            
            if (ch == 'M') {
                result += 1000;
            } else if (ch == 'C') {
                if (next_char == 'M') {
                    result += 900;
                    i++;
                } else if (next_char == 'D') {
                    result += 400;
                    i++;
                } else {
                    result += 100;
                }
            } else if (ch == 'D') {
                result += 500;
            } else if (ch == 'X') {
                if (next_char == 'C') {
                    result += 90;
                    i++;
                } else if (next_char == 'L') {
                    result += 40;
                    i++;
                } else {
                    result += 10;
                }
            } else if (ch == 'L') {
                result += 50;
            } else if (ch == 'I') {
                if (next_char == 'X') {
                    result += 9;
                    i++;
                } else if (next_char == 'V') {
                    result += 4;
                    i++;
                } else {
                    result++;
                }
            } else { // if (ch == 'V')
                result += 5;
            }
        }
       System.out.println("\nRoman Number: "+str);
	   System.out.println("Equivalent Integer: "+result+"\n");
    }
}

Sample Output:

Roman Number: DCCVII                                                   
Equivalent Integer: 707

Flowchart:

Flowchart: Convert Roman number to an integer number.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to reverse an integer number.
Next: Write a Java program to convert an integer value to absolute value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe