Roman to integer java: In the previous article, we have seen Java Program to Reverse an Integer Number
In this article we will see how we can convert Roman numbers to an integer number by using Java programming language.
Java program to Convert Roman Number to an Integer Number
Approach:
- Create scanner class object.
- Take user input for the roman string.
- Initialize three variables
result
,prev
andcurr
to 0. - Scan the the string from end to start.
- Get the corresponding integer value from the user-defined method
getValue()
and check if it’s value is less than previous scanned roman character then subtract current value from the result else add it. - Return the result.
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // create scanner class object Scanner sc = new Scanner(System.in); // take input from user System.out.print("Enter a roman number: "); String roman = sc.nextLine(); // convert roman to integer int result = romanToInt(roman); // print result System.out.println("Integer value: " + result); } //romanToInt() user defined method to convert roman number to integer private static int romanToInt(String roman) { // declare variables int result = 0; int prev = 0; int curr = 0; // convert roman to integer for (int i = roman.length() - 1; i >= 0; i--) { // get current and previous character curr = getValue(roman.charAt(i)); if (curr < prev) { result -= curr; } else { result += curr; } prev = curr; } return result; } private static int getValue(char charAt) { switch (charAt) { case 'I': case 'i': return 1; case 'V': case 'v': return 5; case 'X': case 'x': return 10; case 'L': case 'l': return 50; case 'C': case 'c': return 100; case 'D': case 'd': return 500; case 'M': case 'm': return 1000; default: return 0; } } }
Output: Case-1 Enter a roman number: II Integer value: 2 Case-2 Enter a roman number: XI Integer value: 11
Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.
Related Java Programs: