How to work with Roman numbers in java


Hello everyone There is a task: write a calculator

  • The calculator can work with Arabic and Roman numbers
  • must accept numbers from 1 to 10 inclusive, no more than
  • The calculator can only work with integers

Code:

import java.util.Scanner;

public class MainClass {
    public static void main(String[] args) {
        int value1 = 0;
        int value2 = 0;
        String operation = null;

        System.out.println("Введите 2  целых числа: ");
        Scanner scanner = new Scanner(System.in);
        if (value1 > 0 || value1 < 10) {
            value1 = scanner.nextInt();
            operation = scanner.next();
            value2 = scanner.nextInt();
        }
        if (operation.equals("+")) {
            System.out.println(value1 + value2);
        }
        if (operation.equals("-")) {
            System.out.println(value1 - value2);
        }
        if (operation.equals("*")) {
            System.out.println(value1 * value2);
        }
        if (operation.equals("/")) {
            System.out.println(value1 / value2);
        } else {
            System.out.println("error!");
        }
    }
}

Question: How can I do the same with Roman numbers?

Author: omur turdubekov, 2019-09-06

3 answers

Make your own dictionary

string [] arab = new string[10]{"10","1","2","3","4","5","6","7","8","9"};
string [] rome = new string[10]{"X","I","II","III","IV","V","VI","VII","VIII","IX"};

And accordingly change the index, first determining the desired number.

 1
Author: OYBEK RUSTAMOV, 2019-09-06 10:00:57

You can use the enumeration and define the conversion methods you need in it

enum RomanNumeral {
  I("I", 1), IV("IV", 4);...и т.д.

  private int value;
  private String key;

  RomanNumeral(String key, int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
    public String getKey() {
      return key;
    }
    static int toInt(String key) {
      for (RomanNumeral i: this.values())
        if (i.getKey.equals(key))
          return i.getValue();

      return "";
    }
  }
 1
Author: Meer, 2020-05-14 09:09:52

You will need two additional methods: one will convert any Arabic number to Roman, and the other will convert any Roman number to Arabic.

For example, you received the strings "IV" and "X". First, you convert each one to an Arabic number, then perform a mathematical operation with them just as you are doing now, and then convert the result back to the Roman system. There are many examples of conversion logic, for example, this one.

 0
Author: coolsv, 2019-09-06 08:47:53