I'd like to know to set an entry to validate if a String is empty or not empty in a switch-case statement. Let me show you:
String str = 'value'
switch(str){
case str == '':
println('Entered an empty value')
break
case str != '':
println('Entered value ' str)
break
case 'CoDe':
println('Entered special code ' str)
break
default:
println('Incorrect entry')
break
}
I know how to set an entry with a value (case 3) but I don't know how to set a entry with an empty or not empty string value.
Any help?
CodePudding user response:
As commented, what you need in Java is a series of if
tests.
In the String
class, you can test either:
- The string has no characters at all (
isBlank
) - The string has no characters OR has only whitespace characters (
isEmpty
)
if ( str.isEmpty() ) { System.out.println( "ERROR - String has no characters." ); }
else if ( str.isBlank() ) { System.out.println( "ERROR - String has only whitespace." ); }
else if ( str.equals( "CoDe" ) ) { System.out.println( "Code received." ); }
else { System.out.println( "ERROR - Incorrect entry." ); }
See that code run live at Ideone.com.
Before that code block, I would add a null-check.
Objects.requireNonNull( str ); // Throw exception if null.
I find the if - else if - else
construct in Java to be awkward in terms of readability. The switch
syntax is much better at making obvious that a series of possibilities is being tested, mutually-exclusive, with a single result.
I do wish Java offered a cascading test for a series of boolean expressions. I have used such a feature in another language. There I found the cascading-boolean-tests to be quite practical for handling a series of business rules. But, alas, no such feature in Java. If only Brian Goetz were taking my calls.
I do not know Groovy. Perhaps Groovy provides another facility.
CodePudding user response:
I tested it, and I think I have the answer for you.
switch(str){
case "": // empty
println("Entered an empty value")
break
case "CoDe": // str == CoDe
println("Entered special code " str)
break
default: // String not empty and not "CoDe"
println("Not empty")
break
}
It works because you have case ""
which is the empty string. Meaning that everithing else is not empty. everything else is the default:
If you are not convinced, I'll give you a different example with the same meaning.
if(str.isEmpty()) {
// do something
} else if(!str.isEmpty()) { // <- this if is redundant
// do something else
}
You don't need the second if, because, you enter the else brench only if str is not empty! I appleid the same logic to the case. And it works because case "":
in Java is valid.