课堂作业有误

时间:2011-11-01 03:29:50

标签: java

我的代码出错了,我该如何修复此问题。基本上是最好的(入门级)方式从字符串中拉出第二个字符(如果它在那里)。

编辑:错误是

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
        String index out of range: 1
    at java.lang.String.charAt(String.java:686)
    at RomanNumeral.main(RomanNumeral.java:38)

我的代码:

import java.util.Scanner;

public class RomanNumeral {

    public static void main(String[] args) {
        // Declare Variable
        int total = 0, length = 0;
        int first;
        int second;
        String romanNumerals;

        // Declare Scanner
        Scanner in = new Scanner(System.in);

        // Get Input
        System.out.println("Please input a Roman Numeral: ");

        romanNumerals = in.next();

        length = romanNumerals.length();

        while (length != 0) {
            first = valueFinder(romanNumerals.charAt(0));

            if (length > 1) {
                second = valueFinder(romanNumerals.charAt(1));
            } else {
                second = 0;
            }

            if (first >= second || length == 1) {
                total += first;
                romanNumerals = romanNumerals.substring(1);
                System.out.println(romanNumerals);
            }// End of if
            else {
                total += (second - first);
                romanNumerals = romanNumerals.substring(2);
                System.out.println(romanNumerals);
            }// End of Else

        }// End of loop
        System.out.println(total);

    }// End of Main Method

    // valueFinder Method

    public static int valueFinder(char numeral) {
        int value = 0;
        switch (numeral) {
            case 'I':
                value = 1;
                break;
            case 'V':
                value = 5;
                break;
            case 'X':
                value = 10;
                break;
            case 'L':
                value = 50;
                break;
            case 'C':
                value = 100;
                break;
            case 'D':
                value = 500;
                break;
            case 'M':
                value = 1000;
                break;
            default:
                System.out.println(numeral 
                                + " is not a Roman Numeral, and will be ignored.");
                break;
        }// End of Switch
        return value;

    }// End of Method

}// End of Class

1 个答案:

答案 0 :(得分:3)

您需要在获取length的子字符串后更新romanNumerals变量。当你对它进行子串时,字符串本身会变短,但是你所指的数字不是。在需要时调用string.length()方法会更简单,因为这样就无需维护length变量。

或者,创建另一个方法来修改字符串和长度计数器(将其命名为subStringAndUpdateLength())。但这太过分了。