在 case 条件下使用 char 的 switch 语句? [英] switch statement using char in the case condition?
问题描述
我正在尝试编写一个 switch 语句,该语句使用一个字符来表示每种情况.在我的教科书中,示例显示我可以使用字符来执行此操作,但是当我编译我的程序时,我得到了这个:
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
这是我的代码:
switch (inputCode) {
case 'R':
System.out.println("\nEnter file name:");
fileName = menuApp.nextLine();
if (inputCode.trim().length() == 0) {
break; // no file name entered
}
推荐答案
看起来 inputCode
的类型是 String
,而不是 char
... 所以如果您使用的是 Java 7,您只需要将其更改为:
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":
或者,将 inputCode
的类型更改为 char
,在其他地方进行适当的调整.(如果您没有使用 Java 7,这将是您唯一的选择 - 但我怀疑您正在使用 Java 7,否则您会得到不同的编译器错误.)
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.)
这篇关于在 case 条件下使用 char 的 switch 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!