Convert Roman Number To An Integer | Java Programs

Output:

This Program Needs A Little Improvement!

*** Roman Number To Integer Number ***

Use These Symbols -  I, V, X, L, C, D, M
Enter Roman Number: DCLX

Roman Number: DCLX 
Integer: 660

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

public class ConvertRomanToInteger {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("This Program Needs A Little Improvement!" + "\n");
        System.out.println("*** Roman Number To Integer Number ***" + "\n");
        System.out.println("Use These Symbols -  I, V, X, L, C, D, M");
        System.out.print("Enter Roman Number: ");
        String str = scanner.next();
        int length = str.length();
        str = str + " ";
        int result = 0;
        for (int i = 0; i < length; i++) {
            char ch = str.charAt(i);
            char nextChar = str.charAt(i + 1);

            if (ch == 'M') {
                result += 1000;
            } else if (ch == 'C') {
                if (nextChar == 'M') {
                    result += 900;
                    i++;
                } else if (nextChar == 'D') {
                    result += 400;
                    i++;
                } else {
                    result += 100;

                }
            } else if (ch == 'D') {
                result += 500;
            } else if (ch == 'X') {
                if (nextChar == 'C') {
                    result += 90;
                    i++;
                } else if (nextChar == 'L') {
                    result += 40;
                    i++;
                } else {
                    result += 10;
                }
            } else if (ch == 'L') {
                result += 50;
            } else if (ch == 'I') {
                if (nextChar == 'X') {
                    result += 9;
                    i++;
                } else if (nextChar == 'V') {
                    result += 4;
                    i++;
                } else {
                    result++;
                }
            } else { // if (ch == 'V')
                result += 5;
            }
        }

        System.out.println("\nRoman Number: " + str);
        System.out.println("Integer: " + result + "\n");
    }
}
Share This :

Related Post

avatar

good article.thank you for sharing useful info.
visit
web programming tutorial
welookups

delete 29 August 2018 at 20:14



sentiment_satisfied Emoticon