简体   繁体   中英

Java - convert char input (representing Roman Numeral) to decimal equivalent

as the title suggests I am writing a simple prog using methods, that converts the char input of a Roman Numeral between ("M", "D", "C", "L", "X", "V", "I") And then printing the decimal equivalent.

I have written the program but it converts the decimal (int) to Roman Numeral

When modifying the program to accepts char input only to ("M", "D", "C", "L", "X", "V", "I") then outputting decimal, I get errors since char cannot be converted to int.

Any suggestions on how I would change this. Thanks

import java.util.Scanner;

class RomanNumeral {
    public static String romanNumeralToInt(int romanNumeral) {
        String Numeral = "";
        int repeat;

        int value[] = {1000, 500, 100, 50, 10, 5, 1 };
        String symbol[] = {"M", "D", "C", "L", "X", "V", "I" };

        for(int x = 0; romanNumeral > 0; x++) {
            repeat = romanNumeral / value[x];

            for(int i = 1; i <= repeat; i++) {
                Numeral = Numeral + symbol[x];
            }

            romanNumeral = romanNumeral % value[x];
        }

        return Numeral;
    }

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);

        final String INVALID = "Invalid number, try again!";

        final int VALIDATE_NUMBER_1 = 1;
        final int VALIDATE_NUMBER_5 = 5;
        final int VALIDATE_NUMBER_10 = 10;
        final int VALIDATE_NUMBER_50 = 50;
        final int VALIDATE_NUMBER_100 = 100;
        final int VALIDATE_NUMBER_500 = 500;
        final int VALIDATE_NUMBER_1000 = 1000;

        while (true) {
            System.out.print("Enter a number: ");
            int inputValue = input.nextInt();

            if (inputValue == VALIDATE_NUMBER_1) {
                System.out.println(VALIDATE_NUMBER_1 + " = " + romanNumeralToInt(1));
            }
            else if (inputValue == VALIDATE_NUMBER_5) {
                System.out.println(VALIDATE_NUMBER_5 + " = " + romanNumeralToInt(5));
            }
            else if (inputValue == VALIDATE_NUMBER_10) {
                System.out.println(VALIDATE_NUMBER_10 + " = " + romanNumeralToInt(10));
            }
            else if (inputValue == VALIDATE_NUMBER_50) {
                System.out.println(VALIDATE_NUMBER_50 + " = " + romanNumeralToInt(50));
            }
            else if (inputValue == VALIDATE_NUMBER_100) {
                System.out.println(VALIDATE_NUMBER_100 + " = " + romanNumeralToInt(100));
            }
             else if (inputValue == VALIDATE_NUMBER_500) {
                System.out.println(VALIDATE_NUMBER_500 + " = " + romanNumeralToInt(500));
            }
             else if (inputValue == VALIDATE_NUMBER_1000) {
                System.out.println(VALIDATE_NUMBER_1000 + " = " + romanNumeralToInt(1000));
            }
             else {
                 System.out.println(INVALID);
             }
        }

    }
}

UPDATE Code modified as suggested from post, althought still has errors as String cannot be converted to Int. Any suggestions. Thank you

import java.util.Scanner;

class RomanTest {
        public static int romanNumeralToInt(char romanNumeral) {
        String Numeral = "";
        int repeat;

        int value[] = {1000, 500, 100, 50, 10, 5, 1 };
        char symbol[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I' };

        for(char x = 0; romanNumeral > 0; x++) {
            repeat = romanNumeral / value[x];

            for(int i = 1; i <= repeat; i++) {
                Numeral = Numeral + symbol[x];
            }

            romanNumeral = romanNumeral % value[x];
        }

        return Numeral;
    }

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);

        final String INVALID = "Invalid number, try again!";

        final char VALIDATE_CHAR_M = 'M';
        final char VALIDATE_CHAR_D = 'D';
        final char VALIDATE_CHAR_C = 'C';
        final char VALIDATE_CHAR_L = 'L';
        final char VALIDATE_CHAR_X = 'X';
        final char VALIDATE_CHAR_V = 'V';
        final char VALIDATE_CHAR_I = 'I';


        while (true) {
            System.out.print("Enter a number: ");
            char inputValue = input.nextLine().charAt(0);

            if (inputValue == VALIDATE_CHAR_M) {
                System.out.println(VALIDATE_CHAR_M + " = " + romanNumeralToInt('M'));
            }
            else if (inputValue == VALIDATE_CHAR_D) {
                System.out.println(VALIDATE_CHAR_D + " = " + romanNumeralToInt('D'));
            }
            else if (inputValue == VALIDATE_CHAR_C) {
                System.out.println(VALIDATE_CHAR_C + " = " + romanNumeralToInt('C'));
            }
            else if (inputValue == VALIDATE_CHAR_L) {
                System.out.println(VALIDATE_CHAR_L + " = " + romanNumeralToInt('L'));
            }
            else if (inputValue == VALIDATE_CHAR_X) {
                System.out.println(VALIDATE_CHAR_X + " = " + romanNumeralToInt('X'));
            }
             else if (inputValue == VALIDATE_CHAR_V) {
                System.out.println(VALIDATE_CHAR_V + " = " + romanNumeralToInt('V'));
            }
             else if (inputValue == VALIDATE_CHAR_I) {
                System.out.println(VALIDATE_CHAR_I + " = " + romanNumeralToInt('I'));
            }
             else {
                 System.out.println(INVALID);
             }
        }

    }
}

First of all you should pay attention public static int romanNumeralToInt(char romanNumeral) it should return int, but you are returning String Numeral = ""; - it's String, Java as C# is strongly typed language, so you have to return String. Second: concatenating String in way you are doing for(int i = 1; i <= repeat; i++) { Numeral = Numeral + symbol[x]; } for(int i = 1; i <= repeat; i++) { Numeral = Numeral + symbol[x]; } is not recommended (too slow, String is immutable so on every concatenation you are creating new String). Better approach is to use StringBuilder.

I've modified your code and came with something like :

private String decimalToRoman(int number) {
    String[] romans = {"M", "CM", "D", "C", "XC", "L", "X", "IX", "V", "I"};
    int[] values = {1000, 900, 500, 100, 90, 50, 10, 9, 5, 1};
    StringBuilder builder = new StringBuilder();


    for (int i = 0; i < values.length; i++) {
        int times= number / values[i];

        if (times== 0) {
            continue;
        }

        if (times == 4 && i > 0) {
            builder.append(romans[i]);
            builder.append(romans[i - 1]);
        } else {
            for (int ii = 0; ii < times; ii ++) {
                builder.append(romans[i]);
            }
        }

        number = number % values[i];
    }
    return builder.toString();
}

You are doing very things in the wrong way. Here is one way to do.

class RomanNumeral {

    public static void romanNumeralToInt(String romanNumeral) {

        Map<Character,Integer> mapping = new HashMap<>();
        mapping.put('M',1000);
        mapping.put('D',500);
        mapping.put('C',100);
        mapping.put('L',50);
        mapping.put('X',10);
        mapping.put('V',5);
        mapping.put('I',1);

        int result = 0;
        for(char each : romanNumeral.toCharArray()){
            if(mapping.containsKey(each)){
                result += mapping.get(each);    
            }
            else{
                System.out.println("Invalid number");
                return;
            }
        }
        System.out.println(result);
    }

    public static void main(String args[]) {    
        Scanner input = new Scanner(System.in); 
        System.out.print("Enter a number: ");
        String inputValue = input.nextLine();
        romanNumeralToInt(inputValue);
    }

}

The code in the main method already just accept the values 1000, 500, 100, 50, 10, 5, 1. Then in your romanNumeralToInt, there is some operations which are not necessary. Because you already have two arrays mapping for example 1 to I or 5 to V. If you find the index of 1 in the int array then your roman numeral is symbol[foundIndex]. I did not get the the purpose of those two for loops.

I get errors since char cannot be converted to int.

char can be converted to int. But "M" is not char, it is a String. 'M' is a char.

You can get a char from the user in the following way:

char charValue = input.nextLine().charAt(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM