Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class RomanNumeral {
- /*
- * Description:
- *
- * In this program, you are to create a Roman Numeral class to handle Roman
- * numeral operations. The class is supposed to convert numerical input to
- * Roman numerals, and vice versa.
- */
- private static String[] romanNumerals = { "M", "CM", "D", "CD", "C", "XC",
- "L", "XL", "X", "IX", "V", "IV", "I" };
- private static int[] numbers = { 1000, 900, 500, 400, 100, 90, 50, 40, 10,
- 9, 5, 4, 1 };
- private static String resultString = "";
- private static int resultInt = 0;
- public static String numberToRomanNumeral(int input) {
- String result = "";
- for (int i = 0; i < numbers.length; i++) {
- if (input - numbers[i] >= 0) {
- input -= numbers[i];
- result += "" + romanNumerals[i];
- }
- }
- return result;
- }
- public static int romanNumeralToNumber(String input) {
- int result = 0;
- for (int i = 0; i < romanNumerals.length; i++) {
- while (input.startsWith(romanNumerals[i])) {
- result += numbers[i];
- input = input.substring(romanNumerals[i].length());
- }
- }
- return result;
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out
- .println("Enter 1 to have a Roman numeral converted to a number"
- + " or 2 to have a number converted into a Roman Numeral.");
- String choice = scanner.nextLine();
- int choiceInteger = 0;
- try {
- choiceInteger = Integer.parseInt(choice);
- } catch (NumberFormatException e) {
- System.out.println("You didn't enter a valid option.");
- System.exit(1);
- }
- switch (choiceInteger) {
- case 1: {
- System.out
- .println("Enter the Roman Numeral to be converted into an integer");
- String input = scanner.nextLine().toUpperCase();
- if (input.matches("[MCDXLVI]*")) {
- resultInt = RomanNumeral.romanNumeralToNumber(input);
- System.out.println(input + " is " + resultInt);
- break;
- }
- else
- System.out.println("You didn't enter a Roman Numeral. Try again.");
- System.exit(1);
- }
- case 2: {
- System.out
- .println("Enter the number to be converted into a Roman numeral");
- String input = scanner.nextLine();
- int inputInt = 0;
- try {
- inputInt = Integer.parseInt(input);
- } catch (NumberFormatException e) {
- System.out.println("You didn't enter an integer!");
- System.exit(1);
- }
- resultString = RomanNumeral.numberToRomanNumeral(inputInt);
- System.out.println(inputInt + " is " + resultString);
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement