0
我得到一個錯誤與我的代碼,我該如何去解決這個問題。基本上什麼是最好的(入門級)的方式來拉第二個字符的字符串,如果它在那裏。作業上的錯誤
編輯:錯誤是
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
你可以發佈錯誤..?它會幫忙的。 –
@ Pnchappy92:我編輯了你的問題來改進格式。僅供將來參考,您可以突出顯示問題中的一段代碼,並使用文本框上方的按鈕自動格式化代碼。 –