Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // for user input
- public class Roman2Decimal {
- /**
- * Program: Roman2Decimal.java
- * Purpose: Convert Roman numerals to decimal numbers
- * Creator: Chris Clarke
- * Created: 01.11.2012
- */
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- String roman;
- if (args.length > 0)
- roman = args[0];
- else {
- System.out.print("Enter Roman numerals for conversion: ");
- roman = scan.nextLine();
- }
- System.out.println("In decimal: " + convertNumeralToNumber( roman));
- } // end main
- private static int convertNumeralToNumber (String numeral) {
- // read the string from left to right
- int number = 0;
- int first = 0, second = 0;
- numeral = numeral.toUpperCase();
- // while the string isn't empty
- while (!numeral.equals("")) {
- // first numeral
- first = getNumber( numeral.substring(0, 1));
- if (numeral.length() > 1)
- // second numeral
- second = getNumber( numeral.substring(1, 2));
- else
- second = 0;
- // if first numeral is less than second numeral
- if (first < second) {
- // subtract first from second, add result to number
- number += (second - first);
- // remove first two numerals from string
- numeral = numeral.substring(2, numeral.length());
- } else {
- // add value of first numeral
- number += first;
- // remove first numeral from string
- numeral = numeral.substring(1, numeral.length());
- }
- } // end while
- return number;
- } // end convertNumeralToNumber
- public static int getNumber(String letter) {
- switch (letter) {
- case "I": return 1;
- case "V": return 5;
- case "X": return 10;
- case "L": return 50;
- case "C": return 100;
- case "D": return 500;
- case "M": return 1000;
- default : System.out.println("Error: wrong Roman numeral!");
- System.exit(1);
- } //end switch
- return -1;
- } // end getNumber
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement