Switch statement displaying all cases problem [duplicate] - java

Can someone explain me why my loop is going from 0 to 7? I need to get only in the first 3 cases, but the program is going through all.. The code is in the show() method.
for(brojac=0; brojac<3; brojac++){
switch(brojac){
case 1:
figura1.setPosition(pomx[random], pomy[random]);
stage.addActor(figura1);
System.out.println("1");
case 2:
figura2.setPosition(pomx[random], pomy[random]);
stage.addActor(figura2);
System.out.println("2");
case 3:
figura3.setPosition(pomx[random], pomy[random]);
stage.addActor(figura3);
System.out.println("3");
case 4:
figura4.setPosition(pomx[random], pomy[random]);
stage.addActor(figura4);
System.out.println("4");
case 5:
figura5.setPosition(pomx[random], pomy[random]);
stage.addActor(figura5);
System.out.println("5");
case 6:
figura6.setPosition(pomx[random], pomy[random]);
stage.addActor(figura6);
System.out.println("6");
case 7:
figura7.setPosition(pomx[random], pomy[random]);
stage.addActor(figura7);
System.out.println("7");
}
}

Because the break is missing. After every case you need the break keyword. For a detailed explanation see switch statement java tutorial
e.g.
for(brojac=0; brojac<3; brojac++){
switch(brojac){
case 1:
figura1.setPosition(pomx[random], pomy[random]);
stage.addActor(figura1);
System.out.println("1");
break; /// Break here
case 2:
figura2.setPosition(pomx[random], pomy[random]);
stage.addActor(figura2);
System.out.println("2");
break; /// Break here
case 3:
figura3.setPosition(pomx[random], pomy[random]);
stage.addActor(figura3);
System.out.println("3");
break; /// Break here
case 4:
figura4.setPosition(pomx[random], pomy[random]);
stage.addActor(figura4);
System.out.println("4");
break; /// Break here
case 5:
figura5.setPosition(pomx[random], pomy[random]);
stage.addActor(figura5);
System.out.println("5");
break; /// Break here
case 6:
figura6.setPosition(pomx[random], pomy[random]);
stage.addActor(figura6);
System.out.println("6");
break; /// Break here
case 7:
figura7.setPosition(pomx[random], pomy[random]);
stage.addActor(figura7);
System.out.println("7");
break; /// Break here
}
}
Otherwise the other cases will be executed if one of the above cases gets evaluated to true.

That's how Java's switch statements work.
They "fall through" the cases once one of them matches. You need to add break; after all your cases.
for(brojac=0; brojac<3; brojac++){
switch(brojac){
case 1:
figura1.setPosition(pomx[random], pomy[random]);
stage.addActor(figura1);
System.out.println("1");
break;
case 2:
figura2.setPosition(pomx[random], pomy[random]);
stage.addActor(figura2);
System.out.println("2");
break;
case 3:
figura3.setPosition(pomx[random], pomy[random]);
stage.addActor(figura3);
System.out.println("3");
break;
case 4:
figura4.setPosition(pomx[random], pomy[random]);
stage.addActor(figura4);
System.out.println("4");
break;
case 5:
figura5.setPosition(pomx[random], pomy[random]);
stage.addActor(figura5);
System.out.println("5");
break;
case 6:
figura6.setPosition(pomx[random], pomy[random]);
stage.addActor(figura6);
System.out.println("6");
break;
case 7:
figura7.setPosition(pomx[random], pomy[random]);
stage.addActor(figura7);
System.out.println("7");
break;
}
}

Related

How do you set a value (double, String, int, etc.) of a TextField?

private void Button_CalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{ a=Double.parseDouble(TextField_First.getText());
b=Double.parseDouble(TextField_Second.getText());
switch(operation){
case 1:result=a+b;
break;
case 2:result=a-b;
break;
case 3:result=a*b;
break;
case 4:result=a/b;
break;
case 5:result=a%b;
break;
case 6:result=Math.pow(a,b);
break;
case 7:
TextField_Second.setText(""+a);
result=Math.sqrt(a);
TextField_Second.setText(""+a);
break;
case 8:result=Math.abs(a);
default:System.out.println("Please select an operation");
}
TextField_Result.setText(""+result);
}catch(NumberFormatException e){Label_error.setText("Please use your
common sense ;-;");}
}
What I'm trying to do is set the value (and text) of TextField_Second to 0.0, if TextField_Second is null/has no value. So if TextField_First's value is 9, I get the square root, I get an error (NumberFormatException), but I used try and catch, so if that does happen, a label will appear saying, "Please use your common sense ;-;".
P.S. It only works if TextField_Second has a value, and it doesn't affect the answer.
Try something like this;
Note: you have not add break statement to case 8:
try
{
if (!TextField_First.getText().equals(""))
{
if(TextField_Second.getText().equals(""))
{
TextField_Second.setText("0.0");
}
a=Double.parseDouble(TextField_First.getText());
b=Double.parseDouble(TextField_Second.getText());
switch(operation){
case 1:result=a+b;
break;
case 2:result=a-b;
break;
case 3:result=a*b;
break;
case 4:result=a/b;
break;
case 5:result=a%b;
break;
case 6:result=Math.pow(a,b);
break;
case 7:
TextField_Second.setText(""+a);
result=Math.sqrt(a);
TextField_Second.setText(""+a);
break;
case 8:result=Math.abs(a);
break;
default:System.out.println("Please select an operation");
break;
}
}

Apache POI and cyclomatic complexity of code

I have an Excel file, which I am reading using Apache POI APIs; which gives me control over cells/columns in my Excel.
I have around 17 columns in my Excel and these are with different datatypes. I want to populate a model object from these column values. So, I came up with something like below to populate my model object:
private WHTApps populateModel(int columnIndex, Object cellValue) {
WHTApps whtApp = new WHTApps();
switch (columnIndex) {
case 0:
whtApp.setVendorCode((int) cellValue);
break;
case 1:
whtApp.setVendorName((String) cellValue);
break;
case 2:
whtApp.setCountry((String) cellValue);
break;
case 3:
whtApp.setApplicationReceivedFromUSDate((Date) cellValue);
break;
case 4:
whtApp.setContractNumber((String) cellValue);
break;
case 5:
whtApp.setContractEffectiveDate((Date) cellValue);
break;
case 6:
whtApp.setContractExpirationDate((Date) cellValue);
break;
case 7:
whtApp.setAutomaticRenewal((String) cellValue);
break;
case 8:
whtApp.setReducedRate((int) cellValue);
break;
case 9:
whtApp.setForm17((String) cellValue);
break;
case 10:
whtApp.setResidencyCertIssueDate((Date) cellValue);
break;
case 11:
whtApp.setTaxAuthoritySubmissionDate((Date) cellValue);
break;
case 12:
whtApp.setTaxAuthorityAcceptanceDate((Date) cellValue);
break;
case 13:
whtApp.setStatus((String) cellValue);
break;
case 14:
whtApp.setForm17Expiration((Date) cellValue);
break;
case 15:
whtApp.setComments((String) cellValue);
break;
case 16:
whtApp.setRemarks((String) cellValue);
break;
case 17:
whtApp.setCategory((String) cellValue);
break;
default:
}
return whtApp;
}
But, this gives rise to a really high cyclomatic complexity value of 19.
Now how do I reduce the cyclomatic complexity as I have 17 columns which I need to populate in my model object?
Thanks for helping me out
Akshay

Can we call a "case" inside another case in the same switch statement in Java?

My intention is to call two cases inside another case in the same switch statement,
switch (orderType) {
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case 3:
**call case 1;**
**Call case 2;**
break;
default:
break;`
}
Can we do that in Java?
No, you can't jump to the code snippet in another switch case. You can however extract the code into an own method that can be called from another case:
switch (orderType) {
case 1:
someMethod1();
break;
case 2:
someMethod2();
break;
case 3:
someMethod1();
someMethod2();
break;
default:
break;
}
void someMethod1() { ... }
void someMethod2() { ... }
Although you cannot influence the switch cases directly, you can call switch's parent method from one case and pass different arguments. For example,
void foo(int param1, String param2, ...) {
switch (param1) {
case 0:
foo(1, "some string");
break;
case 1:
//do something
break;
default:
break;
}
}
You can't just call a another case block like this. What you could do, though, is wrap each of these blocks in a method, and reuse them:
private void doSomething() {
// implementation
}
private void doSomethingElse() {
// implementation
}
private void runSwitch(int order) {
switch (orderType) {
case 1:
doSomething();
break;
case 2:
doSomethingElse();
break;
case 3:
doSomething();
doSomethingElse();
break;
default:
break;
}
}
Using methods is the best way to do it as mentioned in the accepted answer but for some reasons if you are unable to create method, Here is one more way to do this without using methods
boolean isBreakTheLoop = false, isCase2Required = false;
while(!isBreakTheLoop){
switch (orderType) {
case 1:
statement 1;
if(isCase2Required){
orderType = 2;
break;
}
isBreakTheLoop = true;
break;
case 2:
statement 2;
isBreakTheLoop = true;
break;
case 3:
orderType = 1;
isCase2Required = true;
break;
default:
isBreakTheLoop = true;
break;
}
}
Just a reminder: while the most suggested case is the best solution, note that if you don't close with a brake; your case:, it will continue executing in the next case.
Then, while it's still best pratice to break your cases, you could still adopt a solution similar to the following:
switch (orderType) {
case 3:
someMethod1();
case 2:
someMethod2();
break;
case 1:
someMethod1();
break;
default:
break;
}
Note that "avoiding breaks" solution can't completely cover OP necessities, because writing:
case 3:
case 1:
someMethod1();
case 2:
someMethod2();
default:
break;
or:
case 3:
case 1:
someMethod1();
break;
case 2:
someMethod2();
break;
default:
break;
would make case: 3 be the same than case: 1, making them execute both methods in first code, or a single method in the second code.
You can use this trick in some case :
switch (orderType) {
case 3:
statement 3;
case 2:
statement 2;
case 1:
statement 1;
break;
default:
break;`
}

Java switch case fall through

I have a switch case in Java like this:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
/** For int more than 2, then I need
for it to do something same.
*/
case 3://Do different and case6
break;
case 4://Do different and case6
break;
case 5://Do different and case6
break;
case 6:
break;
}
What is an elegant way to do this, sans having a special case 6 function that case 3-5 calls? (I use int here, but that is an example, so I can't use if(int >2))
A switch can't really do exactly what you are asking out of the box. You can construct something like this with a nested switch though:
outer_switch: switch (example) {
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default: {
switch (example) {
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
case 5: System.out.println("5");
break;
case 6: System.out.println("6");
break;
default: break outer_switch;
}
System.out.println("not 1 nor 2");
}
}
Note the labeled break on outer_switch which is a way to circumvent the shared code if example does not meet any of the inner cases.
One way I could think of is to move your code to different functions. Something like this.
void case1(){
// do something
}
...
void case3(){
// do something
case6();
}
...
void case6(){
// do something
}
// This switch is in some other method.
switch(int example)
{
case 1: //Do different
case1();
break;
...
case 3://Do different and case6
case3(); //internally calls case 6
break;
...
case 6:
case6();
break;
}
Or you can even have different methods for each case and call case3() and case6() methods in the case 3:. Either way, the methods solutions would work, and IMHO, it would be a bit more elegant and multiple switch statements.
I'm not sure if it's elegant, but one way would be to have two switch blocks:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
case 3:
// Do whatever
break;
case 4:
// Do whatever
break;
case 5:
// Do whatever
break;
}
switch(int example)
{
case 3:
case 4:
case 5:
case 6:
// Do whatever (case 3-5 fall through)
break;
}
Although your code is not pretty it's probably going to give you decent performance. Your other obvious option is an if-elseif-else statement. See the accepted answer here for why switch might be the best option, and here to see what performance issues you might run into with large switch statements in Java.
This might also be a solution to what you want to achieve:
switch(example){
case 1:
System.out.println(example);
break;
case 2:
System.out.println(example);
break;
case 3:
System.out.println("I'm case 3");
case 4:
if (example == 4){
System.out.println("I'm case 4");
}
case 5:
if (example == 5){
System.out.println("I'm case 5");
}
case 6:
System.out.println("I'm in extra case " + example);
break;
}
The idea is that you add an extra condition check to let your code fall through all the branches without executing unnecessary ones.

Can I use OR statements in Java switches?

I'm wondering if I can use or in switch-case in Java?
Example
switch (value)
{
case 0:
do();
break;
case 2 OR 3
do2();
break;
}
There is no "or" operator in the case expressions in the Java language. You can however let one case "fall through" to another by omitting the break statement:
switch (value)
{
case 0:
do();
break;
case 2: // fall through
case 3:
do2();
break;
}

Categories

Resources