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;
}
Related
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
I'm on Java 8v60. I tried to embed a switch regarding an exception group in a catch block. Apparently, the case are recognised, but once they get into the switch, they keep going through all the possible cases. Is this a Java bug?
It looks like this:
try {
...
} catch (DateTimeParseException exc) {
...
} catch (myException exc) {
switch (exc.getEvent()) {
case EVENT_ONE :
//once EVENT_ONE gets here;
case EVENT_TWO : case EVENT_THREE :
//it keeps going everywhere;
case EVENT_FOUR :
//and so on;
default :
//and here of course too.
//but if it's not one of the above, it just appears here only
}
...
Weird, isn't it. Any idea?
No. It's not a bug. You are not implemented switch properly. It's fall through. You need to have break after each case.
For ex :
switch (exc.getEvent()) {
case EVENT_ONE :
//once EVENT_ONE gets here;
break;
case EVENT_TWO : case EVENT_THREE :
//it keeps going everywhere;
break;
case EVENT_FOUR :
//and so on;
break;
Here is the official doc for the same
Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
The switch statements jump to the right value, and continue up to the end of other cases.
If you like to exit the switch statement you have to use a break (or return in some situations).
This is useful to handle situations in wich many values can be handled at the same manner:
switch (x) {
case 0:
case 1:
case 2:
System.out.println("X is smaller than 3");
break;
case 3:
System.out.println("X is 3");
case 4:
System.out.println("X is 3 or 4");
break;
}
If the case selection is also a final condition for a method you can return from it.
public String checkX(int x) {
switch (x) {
case 0:
case 1:
case 2:
return "X is smaller than 3";
case 3:
return "X is 3";
case 4:
return ("X is necessary 4");
default:
return null;
}
}
}
Its not java bug. It's your logical bug.
put break statement after each case statement to avoid fall through situation.
My code looks like:
switch(read.nextInt()){
case 1:
//do "a" and print the result
break;
case 2:
//do "b" and print the result
break;
case 3:
//do "a" and print the result
//do "b" and print the result
}
Is there another way to do it without simply copying what's inside case 1 and 2?
I just started my graduation, so I can only use String and Scanner for this, thanks :)
Define two methods called doA() and doB() and call them. This way you won't duplicate your code. Also are you sure you don't need break statements after each case statement?
switch(read.nextInt()){
case 1:
doA();
break;
case 2:
doB();
break;
case 3:
doA();
doB();
break;
default:
// do something
break;
}
A tricky one, IMO more readable:
int nextInt = read.nextInt();
if (nextInt % 2 == 1) { // or if (nextInt == 1 || nextInt == 3) {
// do "a" and print the result
}
if (nextInt > 1) {
// do "b" and print the result
}
In cases like this it probably makes sense to create methods for
//do "a" and print the result
and
//do "b" and print the result
In case 3 you would just call these methods one after the other.
Looks like you've forgot about 'break'. It makes code "break" from switch statement. If you want in case of '1' & '2' do the same thing and in case of '3' the other thing, you can write:
switch(read.nextInt()){
case 1:
case 2:
//do "a" or "b" and print the result
break; //break from switch statement, otherwise, the code below (yes, I mean "case 3") will be executed too
case 3:
//do "a" and print the result
//do "b" and print the result
}
It is a usual thing to add "break" in the end of "case" block if you don't want the same code block to be executed for several values:
switch(n){
case 1:
//do something
break;
case 2:
//do other things
break;
case 3:
//more things!
//you may not write "break" in the last "case" if you want
}
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.
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.