I get a JSON response which roughly looks like this.
{
"status": "success",
"data": [
{
....
}
]
}
The status
field can have two values: success or fail.
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;
}
}
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;
}
But I get the Constant expression required error at each case.
I checked the value returned by Status.SUCCESS.toString()
and Status.FAIL.toString()
which indeed return strings.
Any idea why this error still occur?
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
For example, if a program requires a “const”, but you're feeding it a “variable value”, which can be changed in the program or overwritten. So, use the keyword “const” before that variable to make it a constant and resolve the error.
Strings in switchIt is recommended to use String values in a switch statement if the data you are dealing with is also Strings. The expression in the switch cases must not be null else, a NullPointerException is thrown (Run-time). Comparison of Strings in switch statement is case sensitive.
This error has the following causes and solutions: You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.
case
statements have to be compile-time evaluable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With