How would you rewrite this using a switch statement?

String checkZero(int x)
{
String s;
if (x == 0)
s = "zero";
else
s = "non-zero";
return s;
}

Which do you think is the best choice for this method? Why?

2010-11-09T15:54:44Z

How would this work for Java?

Anonymous2010-11-09T15:48:29Z

Favorite Answer

Switch statements are for many options.

If you mean C/C++, a tertiary operator will be the shortest.

s = x==0?"zero":"non-zero";

Still smaller:

s = x? "non-zero" : "zero";

Smallest:

s = (x?"non-":"") + "zero";

Have fun!
.

odig2010-11-09T23:51:25Z

String checkZero(int x){
switch(x){
case(0):
//whatever
default:
//whatever
}
return s;
}

doesn't really matter what way you do it, i find switch statements are cleaner to look at