简体   繁体   中英

Convert roman numerals to decimal value error

Below I tried to write a program to convert a roman numeral to a decimal value, but I can't seem to figure out why when I enter the test value MCMLXXVIII it prints out 1088 instead of 1978 . If anyone could tell me where I went wrong with this it would be greatly appreciated.

import java.util.Scanner;
public class RomanNumerals {

public static void main(String[] args) {
    Scanner console =  new Scanner(System.in);
    int total = 0, strLength;

    String romanNum;
    System.out.print("Enter roman numeral to convert: ");

    romanNum = console.next();
    total = convertNum(romanNum);

    System.out.println("The roman numeral converted is: " + total);
    console.close();
}

public static int convertNum(String romanNum) {
    int total = 0;
    while (!romanNum.isEmpty())  {
        if ((romanNum.length() == 1) || valueOf(romanNum.charAt(0)) >= 
        valueOf(romanNum.charAt(1))) {
            total += valueOf(romanNum.charAt(0));
            romanNum = romanNum.substring(1);
        } else {
            total += (romanNum.charAt(1)) - (romanNum.charAt(0));
            romanNum = romanNum.substring(2);
        }
    }
    return total;
}

/**
 * Gives the value of the Roman numeral
 *   
 * @param numeral a single Roman numeral
 * @return the decimal value of numeral
 */
public static int valueOf(char numeral) {
    if (numeral == 'I') {
        return 1;
    }
    if (numeral == 'V') {
        return 5;
    }
    if (numeral == 'X') {
        return 10;
    }
    if (numeral == 'L') {
        return 50;
    }
    if (numeral == 'C') {
        return 100;
    }
    if (numeral == 'D') {
        return 500;
    }
    // must be an M
    return 1000;
    }
}

I'm sure that there are easier ways to do this using an array or something else, but for the class I am currently taking we aren't allowed to use arrays and we have to use basic Java stuff like methods and loops, but not arrays because we haven't gotten to them yet.

You forgot to call valueOf() in the else branch:

...

} else {
    total += valueOf(romanNum.charAt(1)) - valueOf(romanNum.charAt(0));
    romanNum = romanNum.substring(2);
}

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