roman numerals to numbers code example

Example 1: roman numbers to numbers

//Java Implementation of Roman To Number


public class RomanToNumber {
	public static int declareIntOfChar(char c)
	{
		int val=0;
		switch(c)
		{
		case 'I':
			val=1;
			break;
		case 'V':
			val=5;
			break;
		case 'X':
			val=10;
			break;
		case 'L' : 
			val=50;
			break;
		case 'C' : 
			val=100;
			break;
		case 'D' : 
			val=500;
			break;
		case 'M' : 
			val=1000;
			break;
		default :
			val=-1;	
			break;
		}
		return val;
	}
	public static void main(String[] args) {
		String s = "XCV";
		int sum = 0,c1,c2;
		for(int i=0;i<s.length();i++)
		{
			c1=declareIntOfChar(s.charAt(i));
			if(i+1<s.length())
			{
				c2=declareIntOfChar(s.charAt(i+1));
				if(c1<c2)
				{
					sum = sum + c2 - c1;
					i++;
				}
				else
				{
					sum = sum + c1;
				}
			}
			else
			{
				sum = sum + c1;
			}
		}
		System.out.print(s + " = " + sum);
	}
}

Example 2: roman numerals converter table embed

const inputField = document.querySelector('input'); // input element
const convertButton = document.getElementById('convert'); // convert button
const outputField = document.getElementById('display'); // output element

Example 3: roman numerals converter table embed

if (/^(0|[1-9]\d*)$/.test(arabic)) {
  // Regular expression tests
  if (arabic == 0) {
    // for decimal points and negative
    outputField.innerHTML = "Nulla"; // signs
  } else if (arabic != 0) {
    for (let i = 0; i < arabicArray.length; i++) {
      while (arabicArray[i] <= arabic) {
        roman += romanArray[i];
        arabic -= arabicArray[i];
      }
    }
    outputField.innerHTML = roman;
  }
} else {
  outputField.innerHTML =
    "Please enter non negative integers only. No decimal points.";
}

Tags:

Java Example