I'm writing a roman numeral program for my class. I'm using a switch statement to convert strings to integers. However I'm getting an incompatible type error when I run it. Im running java 7 so that's not the issue. Here's my code:
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"
is a one character String. 'I'
is the character I, type char
, which is what you need in your case block.
you are trying to match char
(in your switch
()) to String
(at your case blocks) which is invalid
The Switch statement contains a character variable, where as your case refers to string. You need to decide, you want to use string or char and maintain the uniformity throughout.
Here is the code that fixes the above issue.
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.
}
}
}
}