Friday, November 19, 2021

Roman Numeral To Decimal in Java

 A simple program to ask the user to give roman numeral and then the program will convert the given roman numeral into decimal equivalent using Java programming language.

 I am currently accepting programming work, IT projects, school and application development, programming projects, thesis and capstone projects, IT consulting work, computer tutorials, and web development work kindly contact me at the following email address for further details.  If you want to advertise on my website kindly contact me also in my email address also. Thank you.

My email address is the following jakerpomperada@gmail.com, jakerpomperada@aol.com, and jakerpomperada@yahoo.com.

My mobile number here in the Philippines is 09173084360.





Program Listing

import java.util.*;

import java.util.Scanner;  



class Roman_To_Decimal


public static int romanToInteger(String roman) 

 {

    Map<Character,Integer> numbersMap = new HashMap<>();

    numbersMap.put('I',1);

    numbersMap.put('V',5);

    numbersMap.put('X',10);

    numbersMap.put('L',50);

    numbersMap.put('C',100);   

    numbersMap.put('D',500);   

    numbersMap.put('M',1000);  

        

    int result=0;

        

    for(int i=0;i<roman.length();i++)

    {

      char ch = roman.charAt(i);      // Current Roman Character

      

      //Case 1

      if(i>0 && numbersMap.get(ch) > numbersMap.get(roman.charAt(i-1)))

      {

        result += numbersMap.get(ch) - 2*numbersMap.get(roman.charAt(i-1));

      }

      

      // Case 2: just add the corresponding number to result.

      else

        result += numbersMap.get(ch);

    }

        

    return result;

 }

 

  

 public static void main(String args[])

 {

 

Scanner input = new Scanner(System.in);  // Create a Scanner object

 

System.out.println("\n");

System.out.print("\t\tRoman Numeral To Decimal in Java");

System.out.println("\n");

System.out.print("\tGive Roman Numberal Value : ");


    String romanNumber = input.nextLine(); 


    int result = romanToInteger(romanNumber.toUpperCase());

   

    

   System.out.println();

   System.out.println("\tThe Roman Number is: "+romanNumber.toUpperCase());

   System.out.println();

   System.out.println("\tIts Decimal Value is: "+result);

   

   System.out.println();

   System.out.println("\tEnd of Program");

   System.out.println();

   input.close();

 }

}

 


No comments:

Post a Comment