切换不兼容的类型错误

我正在为我的class级写一个罗马数字程序。 我正在使用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; } } 

"I"是一个字符串。 'I'是字符I,键入char ,这是你在case块中需要的。

您正在尝试将char (在您的switch ()中)与String (在您的case块中)匹配,这是无效的

Switch语句包含一个字符变量,在这种情况下引用string。 您需要决定,您想要使用字符串或字符并始终保持一致性。

以下是修复上述问题的代码。

 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. } } } }