0

My instructor gave me a challenge to have a user input a number or roman numeral and have the program convert it to the other. I have made it able to convert an integer to a roman numeral, but I do not know how to do it the other way around. I have tried looking for help, but there is nothing helpful for my situation. Some of you may have given me links or said that this is a duplicate, but, I know how to do the conversion (Yes, I made a HUGE mistake with this question). My problem is being able to do both at once. I do not know how to have it be like: Oh, you entered an integer, convert it to roman numeral, and have it also be like: Oh, roman numeral time! Convert it to an integer. PLEASE HELP!!

import java.util.Scanner;

public class DecimalRoman {
@SuppressWarnings("resource")
public static void main(String args[]) {
    System.out.print("Enter a Number: ");
    Decimal2Roman();
}

public static void Decimal2Roman() {
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();
    if(num>0 && num<4000) //checking whether the number entered is within the range [1-3999]
    {

        /*Saving the Roman equivalent of the thousand, hundred, ten and units place of a decimal number*/
        String thou[]={"","M","MM","MMM"};
        String hund[]={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        String ten[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        String unit[]={"","I","II","III","IV","V","VI","VII","VIII","IX"};

        /*Finding the digits in the thousand, hundred, ten and units place*/
        int th=num/1000;
        int h=(num/100)%10;
        int t=(num/10)%10;
        int u=num%10;

        /*Displaying equivalent roman number*/
        System.out.println("The Roman Numeral of " + num + " is " + thou[th]+hund[h]+ten[t]+unit[u]);
    }

    /*Displaying an error message if the number entered is out of range*/
    else
        System.out.println("\nYou entered a number out of Range.\nPlease enter a number in the range [1-3999]");
}
}
Dylan Black
  • 262
  • 3
  • 16

2 Answers2

2

As per your last EDIT, to recognize what kind of input you get, you can use the Scanner.hasNextInt() method:

Scanner scan = new Scanner(System.in);
if (scan.hasNextInt()) {
    int arabicNumber = scan.nextInt();
} else {
    String romanNumber = scan.next();
}
Carsten
  • 2,047
  • 1
  • 21
  • 46
1

You have to create a index of basic values and match it with numeric values. A little example:

I = 1
V = 5
X = 10

and you have to see the position left/right to sum and subtract. here's the logic, the code is up to you.

Krismorte
  • 642
  • 7
  • 24