在字符串switch语句中恒前pression所需错误

在字符串switch语句中恒前pression所需错误

本文介绍了在字符串switch语句中恒前pression所需错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个JSON响应这大致是这样的。

I get a JSON response which roughly looks like this.

{
  "status": "success",
  "data": [
    {
      ....
    }
  ]
}

状态字段可以有两个值:成功失败

The status field can have two values: success or fail.

所以在我的code,我有以下枚举。

So in my code, I have the following enum.

private enum Status {
    SUCCESS("success", 0),
    FAIL("fail", 1);

    private String stringValue;
    private int intValue;
    private Status(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

我想要做的就是在switch语句,我需要检查的状态值,并在每个条件执行code。

What I want to do is in a switch statement, I need to check for the status value and execute code in each condition.

String status = jsonObj.getString("status");

switch (status) {
    case Status.SUCCESS.toString():
        Log.d(LOG_TAG, "Response is successful!");
    case Status.FAIL.toString():
        Log.d(LOG_TAG, "Response failed :(");
    default:
        return;
}

但我得到的恒前$ P $需要pssion在每种情况下错误。

我检查由 Status.SUCCESS.toString返回的值() Status.FAIL.toString()这的确返回字符串。

I checked the value returned by Status.SUCCESS.toString() and Status.FAIL.toString() which indeed return strings.

知道为什么这个错误仍然出现?

Any idea why this error still occur?

推荐答案

情况语句必须在编译时评估的。

case statements have to be compile-time evaluable.

类似 Status.SUCCESS.toString()不满足这一点。字符串的文字的,而另一方面,确实。

Something like Status.SUCCESS.toString() doesn't satisfy that. A string literal, on the other hand, does.

最明显的解决方法是使用一个如果块。

The obvious fix is to use an an if block.

这篇关于在字符串switch语句中恒前pression所需错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:51