public class Hello {
public static void main(int a) {
switch (a) {
case 1:
System.out.println("Hi");
}
switch (a) {
case 2:
System.out.println("Hello");
}
}
}
Hi,
I want to know if it is possible for me to use Switch Case for the same variable twice, like I've done in the snippet attached.
Thanks.
The code you have provided works. So long as the variable a is in scope, you can use it for as many switch statements as you like.
If you want to check for multiple values of a in the same switch, then you should use different cases. E.g.:
switch (a) {
case 1:
System.out.println("a was 1");
break; // if we did not break, then execution would "fall-through" to the next case
case 2:
System.out.println("a was 2");
break;
default:
System.out.println("a was not 1 or 2");
}
Find out more about the switch statement in the Java Documentation.
Related
I would like to use the switch command with choice defined in a resource file but I have the error:
error: constant expression required
Do you have any suggestion?
ressource file integers.xml
<integer name="readID">0x21</integer>
<integer name="readRevision">0x22</integer>
java file:
switch (cmd) {
case getResources().getInteger(R.integer.readID):
break;
case getResources().getInteger(R.integer.readRevision):
Log.d(TAG, "case revision");
break;
In Java the case part of a switch needs a constant value.
Java expects with getResources().getInteger(R.integer.readID) since it is a method call that the value may change at runtime.
See Java switch statement: Constant expression required, but it IS constant
for more information.
You may use an if, else if, else construct.
Just define your integers as static constants in a separate file (Constants.java perhaps).
Constants
public class Constants{
public static final int READ_ID = 0x11;
public static final int READ_REVISION = 0x22;
}
Switch
switch (cmd) {
case Constants.READ_ID:
break;
case Constants.READ_REVISION:
break;
}
Try
private int getInt(#IntegerRes int res){
return context.getResources().getInteger(res);
}
For example:
switch (cmd) {
case getInt(R.integer.readID):
break;
case getInt(R.integer.readRevision):
Log.d(TAG, "case revision");
break;}
I have a jsp+servlet web application, which runs on tomcat server. All the strings which i use are hardcoded now. If possible I want to move all the hardcoded strings to one resource file and point to particular string in jsp code. How can i do it. Is there any other way other than resource file.For example: In below switch statement, i want to remove all hardcoded strings in case statement and move to one resource file or so and point to that string in my code.
switch (request.getParameter("mode")) {
case "check1": {
break;
}
case "check2": {
break;
}
case "active_inactive": {
break;
}
default:
break;
}
Use class named Constants for this pupose.
public class Constants{
public static String CHECK_1 = "Check1";
public static String CHECK_2 = "Check2";
}
And use this in anywhere you want.
switch (request.getParameter("mode")) {
case Constants.CHECK_1: {
break;
}
case Constants.CHECK_2: {
break;
}
default:
break;
}
Is it possible to exit (return) from a switch case from a method in the same case?
Given this code:
switch(int blaah) {
case 1:
some code here;
break;
case 2:
myMethod();
some code here;
break;
default:
some code here;
}
public void myMethod() {
if(boolean condition) {
return;
/*I want this return valuates in switch case too.
so the switch case exit without executing the rest of code of "case 2" */
}
some code here;
}
I know the return here just skip the rest of the codes in myMethod. I am looking for something that tells the switch case to stop execution from the method.
It is difficult to give a meaningful solution without the full context.
However...
You can return a boolean result from the method and based on it the switch case can decide to continue or not.
public boolean myMethod() {
if(boolean condition) {
return false;
}
//some code here;
return true;
}
switch(int blaah) {
case 1:
some code here;
break;
case 2:
if (myMethod()) {
//some code here; //Execute only if the method signalled to do so
}
break;
default:
some code here;
}
Another option:
If if(boolean condition) is the first thing you do in the method, you can evaluate it in the switch case itself and can avoid calling the method if it turned out to be true and break immediately.
case 2:
if (boolean condition) {
myMethod();
//some code here;
}
break;
Best option would be
case 2:
if (someCondition) {
myMethod();
}
else {
// some code
}
break;
I have a superclass TetrisPiece, with subclasses for each variation of the piece, i.e.
class PieceI extends TetrisPiece{
}
class PieceJ extends TetrisPiece{
}
etc...
In a different class I have a switch statement based on a random number that creates a random piece
switch(rand){
//I
case 1: {
PieceI pieceI = new PieceI();
break;
}
//T
case 2: {
PieceT pieceT = new PieceT();
break;
}
etc...
default:
break;
}
My intention is to extract the piece that is generated from the scope of the switch statement so I can use it later on in the class.
The switch method obviously does not work because of the scope issue, and I cannot create a superclass array outside of the switch statement because I would have no ability to cast the indices due to randomization.
Any help is appreciated.
Create an instance of the superclass TetrisPiece, and then assign PieceT, PieceI, etc to it inside the switch statement.
TetrisPiece piece;
switch(rand){
//I
case 1: {
piece = new PieceI();
break;
}
//T
case 2: {
piece = new PieceT();
break;
}
etc...
default:
break;
}
I would like to use a switch statement, but I am not able to construct it without either duplicating code or using an accompanying if statement. Is there a way around this?
I have 5 cases, and for all but one of them I would like to perform a certain action. So with a switch statement, I can just do:
switch(x) {
case A:
foo();
break;
case B:
case C:
case D:
case E:
bar();
break;
}
Easy. But the difficulty comes in that I also need to perform another distinct action for each one, so I can't use the fall-through feature of the cases. So I'm reduced to either
switch(x) {
case A:
foo();
baz(0);
break;
case B:
bar();
baz(1);
break;
case C:
bar();
baz(2);
break;
case D:
bar();
baz(3);
break;
case E:
bar();
baz(4);
break;
}
which smells to me because of having to repeat bar() every time, or
switch(x) {
case A:
baz(0);
break;
case B:
baz(1);
break;
case C:
baz(2);
break;
case D:
baz(3);
break;
case E:
baz(4);
break;
}
if (x != A) { bar(); }
which doesn't duplicate any code, but it bothers me that there I need to use both switch and if.
I guess one other alternative would be to use a map, like
Map<X, Integer> m = new HashMap<X, Integer>();
m.put(A, 0);
m.put(B, 1);
m.put(C, 2);
m.put(D, 3);
m.put(E, 4);
if (m.get(x) == 0) {
foo();
} else {
bar();
}
baz(m.get(x));
but now I've introduced a whole data structure just to clean this up. (And when you count the initialization of the map, it's not even that much cleaner.)
Any tips?
Is x by any chance an enum? In which case just move the method to the enum instead of switching.
enum Employee {
SENIOR {
#Override
public int salary() {
return 60;
}
},
JUNIOR {
#Override
public int salary() {
return 40;
}
};
public abstract int salary ();
}
And calling
employee.salary();
Is much better than switching.
Yes; you will have to duplicate method calls, but I think this is correct and clear. Or... use a constructor in your enum. Excuse contrived mix of "Employee" code with "foobar" code.
private final boolean flag;
Employee(int flag) {
this.flag = flag;
}
public int method() {
if(flag) {
secondMethod();
}
alwaysMethod();
}
I would split logic by pass x to baz and create new switch there:
switch(x) {
case A:
foo();
break;
case B:
case C:
case D:
case E:
bar();
baz(x); // < ---
break;
}
void baz(SomeEnum val){
switch(val) {/* ...*/}
}
I guess your cases are fixed so you can use enum and just exclude one of them.
public enum MyCase {
A, B, C, D, E;
}
and the condition
MyCase x;
...
if MyCase.A.equals(x) {
foo();
} else {
bar();
}
baz(x);
// or if the oridnal value is required
baz(x.ordinal);