case giving three results for single switch [duplicate] - java

This question already has answers here:
Why do we need break after case statements?
(17 answers)
why is the wrong "case" being executed after "default" in a switch statement
(5 answers)
Closed 4 years ago.
So I have this piece of code:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
}
}
And this returns: Hi
But when I run
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
case "Bye":
System.out.println("Bye");
}
}
It returns:
Hi
Bye
Why is this.Is there something I missed?

As already stated before, you have to add break; statements for each case if you want to stop at that special one. Your code would then look like this:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
}
}
Another thing you really should do is adding a default case for any non matching input (imagine someone input "Hy" instead of "Hi", there wouldn't be any output for that...):
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
default:
System.out.println("Your input was \"" + x
+ "\", please enter either \"Hi\" or \"Bye\" instead!");
}
}
The default statement is an option for anything that isn't handled in the case statements.
Now back to the breaks... You can handle different cases just the same if you set the breaks only to some of the cases:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
case "Hy":
System.out.println("Hi");
break;
case "Bye":
case "By":
System.out.println("Bye");
break;
default:
System.out.println("Your input was \"" + x
+ "\", please enter either \"Hi\", \"Hy\", \"By\" or \"Bye\" instead!");
}
}
Doing like this, you will receive the same output for "Hi" and "Hy" without duplicating the code that handles both cases.

You should put some break statements at the end of case statements or the execution will propagate to the next case statements. Even if it is counter intuitive, it is sometimes useful.
switch(int n) {
case 1: System.out.println("Hello");
case 2: System.out.println("World");
}
Here switch(1) will display :
Hello
World
And switch(2) will display :
World
But with break statements :
switch(int n) {
case 1:
System.out.println("Hello");
break;
case 2:
System.out.println("World");
break;
}
Here switch(1) will display :
Hello
And switch(2) will display :
World

In switch statement you have to write break at the end of each case.
If you do not write break then it prints all cases.
switch(value)
{
case X:
//do something
break;
case Y:
//do something
break;
default:
//do something
break;
}

Related

Is a switch executing all the cases without stopping?

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.

Writing a program using Switch Case Statement (with the use of letters ABCD not int)

I have my code written in if/else Statement and it is working but I have a problem in writing it using switch statement as it appears that there are problems in my variables and symbols.
Can you please spot what is wrong and help me correct it?
My source code below.
import java.util.Scanner;
import java.io.*;
public class CourseCodeSWITCH {
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case A: code = "Accounting";
break;
case B: code = "Banking and Finance";
break;
case C: code = "Computer Science";
break;
case D: code = "Dentistry";
break;
case E: code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
}
}
You're using A, B, C, as labels, but that's not how a switch statement works. Let's take a look at just one statement:
switch (code) {
case A: code = "Accounting";
break;
You're switching on code... this means you're going to be examining the contents of the code variable.
Next, you declare a case. In the case above, you're effectively saying
if (code == A)
code = "Accounting";
break;
Now, there's a couple things wrong with that. First of all, A is not defined anywhere, so you're immediately going to run into compile-time errors. You probably wanted to use a String value ("A") instead. Second, you're just reassigning code instead of outputting like you did in your original if-statement.
You probably want a switch that looks closer to the following:
switch(code) {
case "A":
System.out.println("Assignment");
break;
case "B":
System.out.println("Banking and Finance");
break;
// and so forth
}
In Java 7/8 you can define the String to compare code to. In earlier versions you may want to use a char or enum.
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case "A":
code = "Accounting";
break;
case "B":
code = "Banking and Finance";
break;
case "C":
code = "Computer Science";
break;
case "D":
code = "Dentistry";
break;
case "E":
code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
Additionally here is an example from Oracle.

Make a switch case execute previous cases

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
}

Switch Case Error Validation

Just starting Java so it's probably a simple question but couldn't find any questions like mine so figured I would post one.
I am writing a "main menu" with options 1-8. I figured out how to error handle when someone types a number larger than 8 and less than 1 but I can't figure out how to give them an error message if they type a character or letter...
while(menuChoice != 8)
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
}
Assuming this compiles, what you're asking would be impossible. You're switching on a number, so you can't check if the number is a character. Your code wouldn't compile if that were possible.
You should take the user input as a String and validate the String. If the String has non-numeric values in it, then throw an error. If it doesn't, convert it to a number then execute your switch.
A better design would be to have a validation layer. Once the input is validated, just assume it's valid thereafter.
Pseudocode:
String input = //
if (containsNonNumerics(input))
throw error
inputAsInt = castToInt(input)
if (outOfRange(inputAsInt)
throw error
switch //your current code goes here
First off, having that while loop is not going to give you the functionality that you want. You should look into how to use KeyAdapter in order to be able to receive input events from the keyboad, e.g. a number being pressed, and then you can validate that it is actually a number, and if it is you can then use your switch statement to determine the proper code to execute.
I am guessing that menuChoice is a character. In which case, you can either do a manual check that
if('0' <= mc && mc <= '9') {
// do your regular checks
}
If it is a string then do a
try {
Integer.parseInt(mc)
} catch (NumberFormatException e) { // Not a number. Do your error reporting stuff }
HTH.
Switch statment work only with numeric types (int, byte, char, short). If you try add in switch anything else the compailer wouldent allowe you in general. But if you somehow (cating or other way) want to add in switch statment varible you must befor check it with if statment if the varible is type that you want.
Example:
if(var instanceof String){
System.out.println("Error we don't acceped type string");
}
else{
switch(var){
....
}
}
Use this function before entering into while loop and display the error message.
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
int menuChoice ;
//Now get input from customer in menuChoice
//Your logic goes herr... example menuChoice = ..whateverinput
//After the input is captured then validate
if(menuChoice <1 || menuChoice >8 )
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
else {
System.out.println("Please Enter Valid Entry");
}

Swtich statement syntax error

I am trying to test if my user submits sensible data , which is later formatted to integer.
Where is the problem with the switch statement? :)
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
You're switching on x which is a String - unless you're using Java 7, you can't use String in a Switch statement.
I expect the error is actually coming from str.startsWith(), where that method is expecting to take a String (which you're checking what it starts with) and returns a boolean, which you can't switch on either.
UPDATE Correcting your code to do what I think you're trying to do:
void convert(String str)
{
int i = 0;
switch (str.charAt(0)) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
Although the shorter way is just to do the Integer.parseInt call, and handling the NumberFormatException that may occur - then you don't need to do the switch at all.
void convert(String str)
{
try {
int i = Integer.parseInt(str);
System.out.println (i);
} catch (NumberFormatException e) {
System.out.println ("Should start with fixnumber");
}
}
You need to either return i; and convert the method signature from void to int, or otherwise expose the data in i to make it worthwhile.
x is a string and in case you test number.
try:
case "string1"
..
break;
case "string2"
..
break;
etc...
If you're trying to test to see if the string entered is an Integer, then I see no reason to have the switch() in the first place. It would be far better behavior to catch the exception raised when trying to work with the function.
Example:
void convert(String str) { // Heads-up: convert has <package> visibility
int i = 0;
try {
i = Integer.parseInt(str);
System.out.println(i);
} catch (NumberFormatException nfe) {
System.out.println ("Should start with fixnumber");
}
}
Your x is a String. The switch statement is attempting to compare it against integer values. You need something like this:
switch (Integer.parseInt(x))
{
// etc...
EDIT: Actually, now that I see that the string is supposed to be the result of a startsWith call, I'm totally confused about what this code is trying to do.

Categories

Resources