java switch statement with multiple cases and case ranges - java

I wanted to find a way to do this in java 6, but it doesn't exist:
switch (c) {
case ['a'..'z']: return "lower case" ;
There was a proposal to add this to the java language some time ago: http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000213.html, has anything materialized in java 7?
What are other ways to rewrite this code in java 6, that would read more like a switch/case:
if (theEnum == MyEnum.A || theEnum == MyEnum.B){
}else if(), else if, else if...

You could do something like:
switch (c) {
case 'a':
case 'b':
case 'c':
//...
doSomething();
break;
}

The simplest thing would be:
if (Character.isLowerCase(c)){
return "lowercase";
}
Which will also work with á ö and the sort

How about this?
if(c>='a' && c<='z')
return "lower case";

To the first part, one options for strings
if(c.equals(c.toLowerCase())) return "lower case";
To the second part, you can use switch with enums....
switch(theEnum){
case A:
case B:
break;
case C:
break;
...
}

Or:
if (inRange(c, 'a', 'z')) {
...
}
or use a regex like normal, or a map, or...
With regards to your enum expression, it depends on what you're actually doing, but it might just be a map with implementations or values.

Related

using method in switch case statements

I was wondering if you could use methods such as 'contains()' in the case of a switch case. I am trying to make the following if statements into a switch case:
String sentence;
if(sentence.contains("abcd")){
// do command a
}
else if(sentence.contains("efgh")){
// do command b
}
else if(sentence.contains("ijkl")){
// do command c
}
else{
//do command d
}
Thank you very much for your help.
actually you can change this if into switch, but its kinda unreadable:
final String sentence;
int mask = sentence.contains("abcd") ? 1 : 0;
mask |= sentence.contains("efgh") ? 2 : 0;
mask |= sentence.contains("ijkl") ? 4 : 0;
switch (mask) {
case 1:
case 1 | 2:
case 1 | 4:
case 1 | 2 | 4:
// do command a
break;
case 2:
case 2 | 4:
// do command b
break;
case 4:
// do command c
break;
default:
// do command d
}
}
No, because the case constant must be either:
A constant expression
Or the name of an enumerator of the same type as the switch expression.
A method call is neither of these.
From the Java Language Specification, section 14.11: The switch statement:
Every case label has a case constant, which is either a constant expression or the name of an enum constant.
Yes, you can get an equivalent bit of code to work using the switch statement assuming you are using JDK 7 or higher. JDK 7 introduced the ability to allow String objects as the expression in a switch statement. This generally produces more efficient bytecode compared to a chain of if-then-else statements invoking the equals method.
String pattern;
String sentence;
if (sentence.contains(pattern))
{
switch (pattern)
{
case "abcd":
// do command a
break;
case "efgh":
// do command b
break;
case "ijkl":
// do command c
break;
default:
// do command d
break;
}
}
Do note however that this only works because the contains method expects a String object, and String objects are now valid inside switch statements. You can't generalize this to work with objects of an arbitrary type.
no you cant. case statements can only compare the values of the thing being "switch"ed. Infact, java only 'recently' started supporting switch statements on Strings, since they are objects and not primitive. In general, switch statements will work only on primitives. The only exception to that, as far as im aware, is for Strings

Boolean logic in switch case statement - Java

switch (i) {
case ("+" || "/"):
setOperator("i");
break;
}
What is the best way to do this in Java?
Of course.
Just use
if(i.equals("+") || i.equals("/")) {
setOperator("i");
}
OR if you have to use a switch statement, you can do it this way:
switch(i) {
case "+":
case "/":
setOperator("i");
break;
}
Basically, you can't really have multiple cases the way you had thought about it. It's not the same structure as an if statement, where you can do various logical operations. Java does not go through and do an if statement for each of the cases.
Instead, each time you have case("foo"), Java sees this as something called a Case Label. It is the reason that we sometimes opt to use switch statements, even though they are very primitive and sometimes not very convenient. Because we have case labels, the computer only has to do one evaluation, and it can jump to correct place and execute the right code.
Here is a quote from a website that may help you:
A switch statement, as it is most often used, has the form:
switch (expression) {
case constant-1:
statements-1
break;
case constant-2:
statements-2
break;
.
. // (more cases)
.
case constant-N:
statements-N
break;
default: // optional default case
statements-(N+1)
} // end of switch statement
This has exactly the same effect as the following multiway if statement, but the switch statement can be more efficient because the computer can evaluate one expression and jump directly to the correct case, whereas in the if statement, the computer must evaluate up to N expressions before it knows which set of statements to execute:
if (expression == constant-1) { // but use .equals for String!!
statements-2
}
else if (expression == constant-2) {
statements-3
}
else
.
.
.
else if (expression == constant-N) {
statements-N
}
else {
statements-(N+1)
}
switch (i) {
case ("+"):
case ("/"):
setOperator("i");
break;
}
yes you can do as: Fall through in swith case
switch (i) {
case "+":
case "/":
setOperator(i);
break;
}

Case insensitive matching in Java switch-case statement

I was wondering if there is a way to perform case insensitive match in java switch case statement. the default implementation is case sensitive. Please see the example below.
public class SwitchCaseTest {
/**
* #param args
*/
public static void main(String[] args) {
switch ("UPPER") {
case "upper" :
System.out.println("true");
break;
default:
System.out.println("false");
break;
}
}
}
So above statement returns false as output. And i am trying make it work for case-insensitive match like String.equalsIgnoreCase() would do. I tried to convert both the string literal to lower case and then compare. but was unable to do so.
If you want to do that: just make sure the input data is in all lowercase, and use lowercase cases...
switch ("UPPER".toLowerCase()) {
case "upper" :
....
Localization issues
Also, the ages old issue of localization strikes again, and plagues this thing too... For example, in the Turkish Locale, the uppercase counterpart of i is not I, but İ... And in return, the I is not transformed to i, but a "dotless i": ı. Don't underestimate this, it can be a deadly mistake...
You try making everything uppercase or lowercase
String str = "something".toUpperCase();
switch(str){
case "UPPER":
}
or
String str = "something".toLowerCase();
swtich(str){
case "lower":
}
or even better use enum (note this is only possible from Java 7)
enum YourCases {UPPER1, UPPER2} // cases.
YourCases c = YourCases.UPPER1; // you will probably get this value from somewhere
switch(c){
case YourCases.UPPER1: ....
break;
case YourCases.UPPER2: ....
}
When using a switch statement you must use "break;" for it to exit the statement, so simply use two cases, one without a break.
switch(choice)
{
case 'I':
case 'i':
//Insert a name
System.out.print("Insert a name to add to the list: ");
input.nextLine();
name = input.nextLine();
nameList.insert(name);
System.out.println();
break;
This way, if either "I" or "i" are entered, both cases will have the same outcome.
try
switch ("UPPER".toUpperCase()) {
case "UPPER" :
To avoid having to use the case expression to verify if it is lowercase or uppercase, I recommend that you use the following:
String value = String.valueOf(userChoice).toUpperCase();
This helps to make the conversion of lowercase to uppercase before doing the evaluation in the switch case.

Jumper in Java?

Is there any syntax that allows you to jump from one line to the other?
example:
System.out.println("line");
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
//goto line2 or something like that??
No, there is no goto statement, but there are several workarounds:
do {
//do stuff
if (condition) break; //this will jump--+
//do stuff // |
} while (false); // |
// here <-----------------------------------+
and
int id = 0;
while (true) {
switch (id) {
case 0:
//do stuff
if (condition) {id = 3; break;} //jumps to case 3:
case 1:
if (condition) {id = 1; break;} //jumps to case 1:
// ...
}
}
You can achieve this in a roundabout way, for example with a switch statement:
switch (lineNum) {
case 1: System.out.println("line 1");
case 2: System.out.println("line 2");
case 3: System.out.println("line 3");
case 4: System.out.println("line 4");
}
Now you must ensure lineNum has the appropriate value.
For any backward jumps you'll need a do or while loop.
Java intentionally does not support goto. This is to encourage (force) you to build the control flow using the proper conditional constructs.
In your example, the proper method would be a while-loop:
System.out.println("line");
while (true) {
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
}
If you think about it, there is no code flow pattern that cannot be expressed without the need for goto (it may require to stray from personal ingrained habits). The only time you may want to use goto is to avoid code duplication. If you encounter such a case, restructuring the code into a separate method that can be called where needed is a much cleaner solution.
There is no goto in Java although it is a reserved keyword.
A goto is considered a bad programming construct and, as such, was left out of Java.
what exactly do you want to achieve? you could use labels as in http://geekycoder.wordpress.com/2008/06/25/tipjava-using-block-label-as-goto/, anyway using goto like statements could lead to spaghetti code

How to do a case with multiple conditions?

In the 1 month experience I've had with any programming language, I've assumed that switch case conditions would accept anything in the parenthesis as a boolean checking thingamajig, ie
these:
|| && < >
Know what I mean?
something like
char someChar = 'w';
switch (someChar) {
case ('W' ||'w'):
System.out.println ("W or w");
}
Sadly, doesn't seem to work that way. I can't have boolean checking in switch case.
Is there a way around it?
By the way, terribly sorry if I'm sounding confusing. I don't quite know the names for everything in this language yet :X
Any answers appreciated
You can achieve an OR for cases like this:
switch (someChsr) {
case 'w':
case 'W':
// some code for 'w' or 'W'
break;
case 'x': // etc
}
Cases are like a "goto" and multiple gotos can share the same line to start execution.
You can do -
switch(c) {
case 'W':
case 'w': //your code which will satisfy both cases
break;
// ....
}
Every case is normally followed by a "break;" statement to indicate where execution should terminate. If you omit the "break;", then execution will continue. You can use this to support multiple cases which should be handled the same way:
char someChar = 'w';
{
case 'W':
// no break here
case 'w':
System.out.println ("W or w");
break;
}
Switch cases are branches for alternative evaluations of a given expression. The expression is given in the switch parenthesis and can be byte, short, char, and int data types.
The body of a switch statement is known as a switch block. A statement
in the switch block can be labeled with one or more case or default
labels. The switch statement evaluates its expression, then executes
all statements that follow the matching case label.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
For an alternate to switch statement(multiple if conditions), I think the best solution will be using an enum. For example: Consider the case below:-
public enum EnumExample {
OPTION1{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the first option.");
return void;
}
},
OPTION2{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the second option.");
return void;
}
},
OPTION3{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the third option.");
return void;
};
public static final String CLASS_NAME = Indicator.class.getName();
public abstract void execute();
}
The above enum can be used in the following fashion:
EnumExample.OPTION1.execute();
Hopefully this helps you guys.

Categories

Resources