我正在为我的班级写一个罗马数字程序。我正在使用switch语句将字符串转换为整数。但是,当我运行它时,我得到一个不兼容的类型错误。我正在运行java 7,所以这不是问题。这是我的代码:
public static void main()
{
// Declare local variables
Scanner input = new Scanner(System.in);
String rNum;
int i;
int[] rArray;
// Display program purpose
System.out.println("This Program Converts Roman numerals to decimals");
System.out.println("The Roman numerals are I (1), V (5), X (10), L (50), C (100), D (500) and M (1000).");
System.out.print("Enter your roman numeral: ");
rNum = input.next().toUpperCase();
rArray = new int[rNum.length()];
for(i = 0; i < rNum.length(); i++){
switch(rNum.charAt(i)){
case "I": rArray[i] = 1;
break;
}
}
答案 0 :(得分:5)
"I"
是一个字符串。 'I'
是字符I,键入char
,这是您在案例块中所需的内容。
答案 1 :(得分:1)
您试图将char
(在您的switch
())与String
(在您的案件区块中)无效匹配
答案 2 :(得分:0)
Switch语句包含一个字符变量,在这种情况下引用字符串。您需要决定,您希望使用字符串或字符并始终保持一致性。
以下是解决上述问题的代码。
class test {
public static void main(){
// Declare local variables
Scanner input = new Scanner(System.in);
String rNum;
int i;
int[] rArray;
// Display program purpose
System.out.println("This Program Converts Roman numerals to decimals");
System.out.println("The Roman numerals are I (1), V (5), X (10), L (50), C (100), D (500) and M (1000).");
System.out.print("Enter your roman numeral: ");
rNum = input.next().toUpperCase();
rArray = new int[rNum.length()];
for(i = 0; i < rNum.length(); i++){
switch(rNum.charAt(i)){
case 'I': rArray[i] = 1;
break;
case 'V': rArray[i] = 1;
break;
case 'X': rArray[i] = 1;
break;
case 'L': rArray[i] = 1;
break;
//Continue in the same manner as above.
//Not sure, if this is the right way to convert and will
//convert all types of number. Just check on this.
}
}
}
}