[英]Android project using Eclipse gives error: Cannot switch on a value of type String for source level below 1.7
I was working on an android project using eclipse and suddenly i started to get this error: 我当时正在使用eclipse开发一个Android项目,突然我开始收到此错误:
Cannot switch on a value of type String for source level below 1.7. 无法打开源级别低于1.7的字符串类型的值。 Only convertible int values or enum variables are permitted. 仅允许使用可转换的int值或枚举变量。
I tried every solution in previous similar issues but none of them worked for me... 在以前的类似问题中,我尝试了所有解决方案,但没有一个对我有用。
I have Tried fixing the project and setting the JDK compliance level to 1.7 in both my project and for all project. 我已尝试修复该项目,并将我的项目和所有项目的JDK遵从性级别设置为1.7。
I am using ADT Build: v22.2.1-833290 and Eclipse: 我正在使用ADT Build:v22.2.1-833290和Eclipse:
String text = mService.getString();
switch (text) {
case Protocols.REQUEST_SEND_MESSAGE:
publishProgress("sent");
break;
case Protocols.RESPONSE_OK:
mService.sendMessage("mesasage");
publishProgress("sent");
break;
default:
break;
}
What's going on? 这是怎么回事?
You are trying to use switch
/ case
with String
objects, which is only available in Java 1.7 or higher. 您正在尝试对String
对象使用switch
/ case
,这仅在Java 1.7或更高版本中可用。 Android ADT requires Java 1.6. Android ADT需要Java 1.6。 This means you cannot use switch
with String
construct. 这意味着您不能将switch
与String
构造一起使用。 Just replace it with if
/ else
. 只需将其替换为if
/ else
。
Replace your code with this. 以此替换您的代码。
String text=mService.getString();
if (Protocols.REQUEST_SEND_MESSAGE.equals(text)) {
publishProgress("sent");
} else if (Protocols.RESPONSE_OK.equals(text)) {
mService.sendMessage("mesasage");
publishProgress("sent");
}
Another option would be to create an enum
and put all Protocol constants into there. 另一个选择是创建一个enum
并将所有协议常量放入其中。 Then you will be able to use switch
/ case
with enum
values. 然后,您将可以使用带有enum
值的switch
/ case
。
As the answer below gives more details, switch statement on String objects is a new feature introduced in Java 1.7. 由于下面的答案提供了更多详细信息,因此String对象上的switch语句是Java 1.7中引入的新功能。 Unfortunatelly Android requires version 1.6 or 1.5. 不幸的是,Android需要版本1.6或1.5。 : :
https://stackoverflow.com/a/14367642/1572408 https://stackoverflow.com/a/14367642/1572408
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.