Reputation: 61
I'm trying to write a switch statement that uses a char to represent each case. In my textbook the examples show I can use a char to do this but when I compile my program I get this:
StudentInvoiceListMenuApp.java:54: error: incompatible types
case 'R':
^
required: String
found: char
1 error
This is my code:
switch (inputCode) {
case 'R':
System.out.println("\nEnter file name:");
fileName = menuApp.nextLine();
if (inputCode.trim().length() == 0) {
break; // no file name entered
}
Upvotes: 1
Views: 3763
Reputation: 240928
inputCode
seems instance of String
and you are trying to compare it with char
,
String in switch is supported with and after java -7
Upvotes: 0
Reputation: 28362
The problem is that inputCode is a string. If you want to look at the first element of the string you should do:
switch (inputCode[0]) {
If you want to compare with a single character string you should do:
case "R":
Upvotes: 1
Reputation: 1502066
Looks like inputCode
is of type String
, not char
... so if you're using Java 7, you just want to change it to:
case "R":
Alternatively, change the type of inputCode
to char
, making appropriate adjustments elsewhere. (If you're not using Java 7, this would be your only option - but I suspect you are using Java 7, as otherwise you'd get a different compiler error.)
Upvotes: 5