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
}
Related
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;
}
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.
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;
}
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");
}
Is there any syntax that allows you to jump from one line to the other?
example:
System.out.println("line");
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
//goto line2 or something like that??
No, there is no goto statement, but there are several workarounds:
do {
//do stuff
if (condition) break; //this will jump--+
//do stuff // |
} while (false); // |
// here <-----------------------------------+
and
int id = 0;
while (true) {
switch (id) {
case 0:
//do stuff
if (condition) {id = 3; break;} //jumps to case 3:
case 1:
if (condition) {id = 1; break;} //jumps to case 1:
// ...
}
}
You can achieve this in a roundabout way, for example with a switch statement:
switch (lineNum) {
case 1: System.out.println("line 1");
case 2: System.out.println("line 2");
case 3: System.out.println("line 3");
case 4: System.out.println("line 4");
}
Now you must ensure lineNum has the appropriate value.
For any backward jumps you'll need a do or while loop.
Java intentionally does not support goto. This is to encourage (force) you to build the control flow using the proper conditional constructs.
In your example, the proper method would be a while-loop:
System.out.println("line");
while (true) {
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
}
If you think about it, there is no code flow pattern that cannot be expressed without the need for goto (it may require to stray from personal ingrained habits). The only time you may want to use goto is to avoid code duplication. If you encounter such a case, restructuring the code into a separate method that can be called where needed is a much cleaner solution.
There is no goto in Java although it is a reserved keyword.
A goto is considered a bad programming construct and, as such, was left out of Java.
what exactly do you want to achieve? you could use labels as in http://geekycoder.wordpress.com/2008/06/25/tipjava-using-block-label-as-goto/, anyway using goto like statements could lead to spaghetti code