阿拉伯数字为罗马,反之亦然

时间:2014-11-30 13:45:59

标签: java netbeans netbeans-7

我必须编写一个Java程序将阿拉伯数字转换成罗马数字,反之亦然,但是我的代码遇到麻烦,有人能告诉我这个例子应该如何看待,因为我不知道它是怎么回事看起来像(

import java.util.*;
public class Du3 {
static int last = 2000;
static int numbers[]  = {1, 4, 5, 9, 10, 50, 100, 500, 1000 };
static String letters[]  = { "I", "IV", "V", "IX", "X", "L", "C", "D", "M"};
           public static void main (String[] args){
                System.out.println("Enter your Roman Numerals or Integer number:");
                Scanner cti = new Scanner(System.in);
                String a = cti.next();
                char c = a.charAt( 0 );
                        char a1=convertRomanToInt(romanValue);
                    if ( Character.isDigit( c ) ){
                        System.out.println("Roman value = " + integerValue);}
                    else {
                        System.out.println("Integer value = " + romanValue);

                                }
    static int convertRomanToInt(String romanNumeral){
        int integerValue = 0;
        for (int i = 0; i < romanNumeral.length(); i++){
            char ch = romanNumeral.charAt( i );
            int number = letterToNumber( ch );
            if ( number == -1){
                throw new NumberFormatException("Invalid format");
            }
            if (last<number)
            number-=last- 1;
            integerValue += number;
            last = number;
        }
        return integerValue;
    }
    private static int letterToNumber(char letter){
        switch (letter) {
            case 'I':  return 1;
            case 'V':  return 5;
            case 'X':  return 10;
            case 'L':  return 50;
            case 'C':  return 100;
            case 'D':  return 500;
            case 'M':  return 1000;
            default:   return -1;
}
}
     static String convertIntegerToRoman(int number){
        String romanValue = "";
        int N = number;
        while ( N > 0 ){
        for (int i = 0; i < numbers.length; i++){
        if ( N < numbers[i] ){
        N -= numbers[i-1];
        romanValue += letters[i-1];
        break;
        }
        }
        }
        return romanValue;
    }
}

1 个答案:

答案 0 :(得分:1)

嗯,这显然是错误的:

char a1=convertRomanToInt(romanValue);

方法convertRomanToInt()会返回int,但您要将其分配给a1,即char

然后你永远不会对a1做任何事情,但你继续尝试打印变量integerValue

if ( Character.isDigit( c ) ){
     System.out.println("Roman value = " + integerValue);}

integerValue仅在convertRomanToInt()方法的范围内声明。它在main()中不可用。