切换不兼容类型错误
问题描述:
我正在为我的班级编写罗马数字程序。我使用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;
}
}
答
你试图匹配char
(在你的switch
())来String
(在你的情况下,块),这是无效的
答
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.
}
}
}
}
'charAt'返回什么值类型? “我”是什么类型? –
Sotirios Delimanolis-虽然你有下面的答案,但有一个很好的观点。今后,以这种方式思考,你会发现你自己的大部分答案。 –
这是一个很好的观点。我对java还是一个新手,并没有意识到有一个字符类型。我会牢记这一点。 – user3317470