Code performed in every case of a switch case solution - java

Suppose i have a piece of code that should be performed in each of the cases of a switch case construct:
switch(myEnum){
case A:
System.out.println("hi from" + myEnum.getName());
break;
case B:
System.out.println("hi from" + myEnum.getName());
break;
...
}
Is there a way to avoid writing the line
System.out.println("hi from" + myEnum.getName());
in each of the cases and defining a method called by each of the cases?

If you have two cases which result int he same action, you could do something like so:
switch(myEnum){
case A:
case B:
System.out.println("hi from" + myEnum.getName());
break;
...
}
The test action for the test case A should trickle down to be handled by B.

If you want
System.out.println("hi from" + myEnum.getName());
to execute in any case, you don't need to put it in switch case.
Also, if you place the statement in case B, and you don't put break statement in case A, then you will execute in both case A and case B

You can fallthrough - Can I use OR statements in Java switches?
case A:
case B:
System.out.println("hi from" + myEnum.getName());

Related

Can we implement a nested switch case in java?

I am writing a menu driven program to perform operations on either of the two stacks Stack1 or Stack2. I am using a switch case to accept user's choice. Suppose if user chooses Stack1 and Case 1 is going to be executed. So inside Case 1 can I create another switch case to ask user's choice to perform push or pop operation.
Is it possible to create nested switches in a java program?
we can write nested switch in java
option=Some user input (scan.nextInt())
`switch(option)
{
case 1:
option2=//some user input
switch(option2){
case 1:
enter code here;
break;
case 2:
enter code here;
break;
//soon
}
break; // Case1 break in first switch case
case 2:
option2=//some input
switch(option2){
case 1:
enter code here;
break;
case 2:
enter code here;
break;
//soon
}
break; // Case2 break in first switch case
default:
break;
Likewise we can nested switch case in java

button action leading to seemingly random action performed [duplicate]

I have this code with the switch statement which I got from this post, and it works absolutely fine:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
But if I change it to something like the following, it breaks, as all the cases besides case 1 gets executed:
static String getOrdinal(final int day) {
StringBuilder ordinalBuilder = new StringBuilder();
ordinalBuilder.append("<sup>");
if (day >= 11 && day <= 13) {
ordinalBuilder.append("th") ;
}
switch (day % 10) {
case 1: ordinalBuilder.append("st");
case 2: ordinalBuilder.append("nd");
case 3: ordinalBuilder.append("rd");
default: ordinalBuilder.append("th");
}
ordinalBuilder.append("</sup>");
return ordinalBuilder.toString();
}
This prints 2<sup>ndrdth</sup> when I pass in 2. I tried changing the builder to buffer but I got the same response... Could this be a bug or am I making some mistake?
It's a bug in your code. You forgot to put in a break after each case:
switch (day % 10) {
case 1: ordinalBuilder.append("st"); break;
case 2: ordinalBuilder.append("nd"); break;
case 3: ordinalBuilder.append("rd"); break;
default: ordinalBuilder.append("th"); break;
}
I don't see any bug here, at least not in the way the language is working. The behavior of a switch statement, by design, is that it will start executing statements at the case label which matches the argument, and then continue until the end of the block. So
switch (x) {
case 1:
// do thing 1
case 2:
// do thing 2
case 3:
// do thing 3
default:
// do nothing
}
will do both things 2 and 3 if x is 2, and will do things 1, 2, and 3 if x is 1.
To get the behavior you're probably looking for, end each case with a break:
switch (x) {
case 1:
// do thing 1
break;
case 2:
// do thing 2
break;
case 3:
// do thing 3
break;
default:
// do nothing
break;
}
(strictly speaking the break at the very end is unnecessary, but I often put it in out of habit).
The reason you didn't have this problem in the first code example is that return is like a super-break: it has the same effect as break, namely ending execution within the switch block, but it also ends execution of the whole method.
you need to add a 'break' statement in every switch case.
It was worked previously because you made a return from method...
A "break;" statement separates the cases from one another so in order to execute the statements in a specific case just break the case as soon as it comes to an end.
If you don't use break the compiler thinks that it can continue execution of all the cases up to the end of the program.
The first version returns before continuing on in the case statement. The second version needs a break; statement to get the same behavior.
Luckily with the introduction of switch statements on Java 12 which also introduced
"arrow case" labels that eliminate the need for break statements to
prevent fall through (source).
Therefore the modern version of your code looks like the following:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
return switch (day % 10) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
}
I see this question is over 8 years old, but this answer should help anyone landing on this page.
Firstly lets's understand how switch cases work. In C, C++, Java, JavaScript, and PHP while executing switch statements all the cases following the satisfactory case are executed, unlike in Go where only selected case is executed.
For example:
public class Main
{
public static void main(String[] args) {
int day = 11;
switch (day % 10) {
case 1: System.out.println("st");
case 2: System.out.println("nd");
case 3: System.out.println("rd");
default: System.out.println("th");
}
}
}
Currently, day value is set to 11 and hence very first case satisfy the condition, and hence all below cases would be executed. The output should look like the one below:
st
nd
rd
th
Now let's change day value to 13 resulting in the third case to satisfy the condition and hence below output is obtained:
rd
th
Hence if you want to break the code after first satisfactory case is found then put break; condition in the end. In the code mentioned in the question return; does the job of breaking the code.
Also, most of the novice java programmers believe that SWITCH statements are syntactical sugar to IF statements wherein programmers don't have to repetitively mention conditions. But that's not the case as IF's are meant to exit after the execution of satisfactory condition while SWITCH still continues execution.
Switch cases can be utilized to achieve the purpose like one mentioned in below example:
wherein
for Grade A "Excellent!" should be printed
for Grade B and C "Well done" should be printed
for Grade D "You passed \n Try hard next time" should be printed
for Grade F "Try hard next time" should be printed
and if not a valid case i.e grade is found than "Invalid Grade" should be printed.
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Try hard next time");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Add a break statement at the end of the every line in each case or just use the return statement.

How to use the switch statement?

I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.
for A, I want to do statement_1 and statement_3.
for B, I want to do statement_2 and statement_3.
for C, I want to do nothing
if I use if-else statement, it will look like this:
if ( not Car){
do statement_3
if Bag
do statement 2
else if Apple
do statement 1
}
when i try to do it from switch statement im getting trouble
switch (variable){
case A: do statement_1
case B: do statement_2
// how to do statement 3 here?
}
The default section handles all values that are not explicitly handled by one of the case statements.
switch(var){
case A:
//do stuff
break;
case B:
//do stuff
break;
default:
//do stuff
break;
}
EDIT: I have just read the question again and I think I understood you, if you want to "do statement_1 and statement_3 for A and statement_2 and statement_3 for B" you just have to write it:
switch(var){
case A:
statement_1
statement_3
break;
case B:
statement_2
statement_3
break;
}
I guess you forgot to add a break statement. For example if expression == A and you don't have break all statements will be executed, whereas if you add break, it will not execute the rest of the cases. Also, the default is the one which is executed if expression doesn't satisfy any of the cases.
switch(expression){
case A:
statement_1
statement_3
break;
case B:
statement_1
statement_2
break;
default:
break;
}
For each case, you have to write all the required "statements" and then add break; otherwise the next case will be also executed:
switch (variable) {
case A:
statement_1;
statement_3;
break;
case B:
statement_2;
statement_3;
break;
case C:
default:
break;
}
Here default case and C case are the same and do nothing.

Combining assert and switch statements

I was answering a Java test and come across the question:
Which of the following statements is true?
A. In an assert statement, the expression after the colon ( : ) can
be any Java expression.
B. If a switch block has no default, adding an assert default is considered appropriate.
C. In an assert statement, if the expression after the colon ( : ) does not have a
value, the assert's error message will be empty.
D. It is appropriate to handle assertion failures using a catch clause.
The right answer is B. To be honest, I answered that question by excluding another obviously wrong cases, but I can't get the point of that question actually. Could anyone explain why it is true? Where can it be helpful?
I guess it means you should protect yourself from missing a switch case.
Say you have an enum Color {red, green} and this switch in the code:
switch(color) {
case red:
doSomethingRed();
break;
case green:
doSomethingGreen();
break;
}
If in the future you add a new color blue, you can forget to add a case for it in the switch.
Adding failing assert to the default case will throw AssertionError and you will discover your mistake .
switch(color) {
case red:
doSomethingRed();
break;
case green:
doSomethingGreen();
break;
default:
assert false : "Oops! Unknown color"
}
This depends on the case but the way I see it
// Consider expecting only 1,2 or 3 as switch case
switch(x)
{
case 1:
// operations
break;
case 2:
// operations
break;
case 3:
// operations
break;
default: assert false : "Input should be between 1-3";
}
Might be convenient as any other input you might receive can be perceived as a faulty input.
Using assert false in switch block's default is applicable in the public method context e.g.
public void methA(int x) throws Exception {
if(x!=1 && x!=2 && x!=3)
throw new IllegalArgumentException("from Exception: x should be between 1,2 and 3");
switch(x)
{
case 1: doSomething(); break;
case 2: doSomething(); break;
case 3: doSomething(); break;
default: assert false : "from default: x should be between 1,2 and 3";
}
}
If the switch block is used in a public method, then checking the value of the argument x is already handled by an exception before the switch statement.
So, even when you use the assert false in default, that code is never reachable, since the assumption that x is 1,2 or 3 is always true. If not true, it is already handled by the IllegalArgumentException before the switch default. So basically, the assumption that switch-default will never be reached is always true. Hence it is appropriate in the context of public method.

Unable to get behaviour of Switch case in java

I have written small code in java 6
public class TestSwitch{
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:{
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
}
case 2:{
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
}
System.out.println("end");
}
}
Output: start 1 2 end
My editor is showing orphaned case for 'case 3' and 'case 5'.Still it is running
and showing output.
Does Nastated cases like concept is there in Java?
And Why it is giving above output? rather i thought it will be 'start 1 end'
Your response will be greatly appreciated!!
Switch replaces if else's but switch syntax != If else syntax.
You forgot to put break after each case.
So conditions under fall through.
Example:
case 0:
mColor.setText("#000000");
break;
You can find that in docs
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.
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
System.out.println(5);
break;
case 7:
System.out.println(7);
break;
default:
System.out.println("nothing");
}
switch(a){
case 1:{
System.out.println(1);
case 3:
You cannot nest cases like this. Switch should look either like :
switch(a){
case 1:
System.out.println(1);
break;
case 3:
....
or like this :
switch(a){
case 1:
System.out.println(1);
switch(a) {
case 3:
//...
break;
case 5 :
//...
And if you don't add break at the end of a case, the execution will continue after. You should add a break at the end of each cases if they should be executed separately.
You have wrong closing braces before case 2.
case 3,4 are interpreted as labels not cases.
Your code will give compilation errors as we can't use curly brace after case :
Exact code is:
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
case 2:
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
System.out.println("end");
}
}
and output will be start
1
3
4
2
5
7
end because you have not use "break" after each case.
As their no break statement in case 1: the execution directly jumps to case 2: and ends up printing "start 1 2 end"..
You have not added break statement before case 2.
Refer this to know more about fall through.
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.
int a = 1;
System.out.println("start");
switch (a) {
case 1: {
System.out.println(1);
break;
}
case 3: {
System.out.println(3);
break;
}
case 4: {
System.out.println(4);
break;
}
case 2: {
System.out.println(2);
break;
}
case 5: {
System.out.println(5);
//no break will fall through and print 7 too
}
case 7: {
System.out.println(7);
break;
}
default:{
System.out.println("none");
}
}
See if a=1 then your case 1 will work then 1 will pe printed if as we have not using break after case 1 so all cases are working in flow so output is coming like this if you want to execute only one case at one time then you have to put break after one case like
switch(a){
case 1:
System.out.println(1);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
Then it will break out of the switch case on encountering break statement

Categories