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
Related
I am working on a program that is a simple game. I'm using a switch statement to return the file location of images that are assigned to buttons. In order to do this I am using a switch statement inside a method called "get Image View" it returns a string that can be fed into an image view that I will need to compare the image in the button to another image elsewhere. I think I may be over-explaining, anyway. my IDE (NetBeans) is telling me that my break statement is unreachable and I can not figure out why. I have used a switch statement that looks very similar to mine and there is an example in my textbook that is also very similar. I know that I still need to have a default return statement I just want to know what's up with my break statements. Thank you in advance!
public String getImageView(int button)
{
switch(button)
{
case 0: System.out.println("error");
case 1: return "1.png";
break;
case 2: return "2.png";
break;
case 3: return "3.png";
break;
case 4: return "4.png";
break;
case 5: return "5.png";
break;
case 6: return "6.png";
break;
case 7: return "7.png";
break;
case 8: return "8.png";
case 9: return "9.png";
case 10: return "10.png";
}
}
You can try something like below :
public String getImageView(int button){
String imageViewName = "";
switch(button)
{
case 0: System.out.println("error");
case 1: imageViewName = "1.png";
break;
case 2: imageViewName = "2.png";
break;
case 3: imageViewName = "3.png";
break;
case 4: imageViewName = "4.png";
break;
case 5: imageViewName = "5.png";
break;
case 6: imageViewName = "6.png";
break;
case 7: imageViewName = "7.png";
break;
case 8: imageViewName = "8.png";
break;
case 9: imageViewName = "9.png";
break;
case 10: imageViewName = "10.png";
break;
}
return imageViewName;
}
Hope this helps.
Well switch-state-statements behaves not like a big if-else-statement.
Consider this code:
int a = 0;
switch (a) {
case 0:
//do something
break;
case 1:
//do something else
break;
default:
//default case
}
Here the first case will be triggered as you can tell by the value of a.
If you want to first case be executed but also want to slip in the second case anyway you can omit the break in the first case.
So this code:
int a = 0;
switch (a) {
case 0:
System.out.println("case 0");
case 1:
System.out.println("case 1");
break;
default:
//default case
}
will output:
case 0
case 1
just like it is in your Code.
So maybe you should consider the break; in your first case. Otherwise it will execute the println but also returning 1.png.
I am expecting my input to be one of three groups of chars and need to decide what to do with it based on which group it falls in. I'm trying to figure out how to define a switch with multiple cases to do this. Here is what I have so far:
while(in.hasNextChar())
{
char test = in.nextChar();
List<Signal> out = new List<Signal>(0);
switch(test)
{
case '1','0','x','X':
out.add(fromString(test));
break;
case ' ','/t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
}
return out;
}
You have the syntax wrong. You need to take advantage of fall-through:
switch(test) {
case '1':
case '0':
case 'x':
case 'X':
out.add(fromString(test));
break;
case ' ':
case '\t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
A case is just a label, very similar to what you'd use with a goto (which is essentially what is happening behind the scenes). It's not a statement, since it does nothing itself — it just names an address. So if test is '0', it can happily continue through the 'x' and 'X' cases to reach the actual statement code since there's not anything being done by those labels. Only break "ends" a case.
You can actually insert code between cases even without a break:
switch(test) {
case '1':
System.out.println("This is printed by case '1'");
case '0':
System.out.println("This is printed by both case '1' and case '0'");
break;
case 'x':
case 'X':
System.out.println("This is only printed by the Xs");
break;
default:
break;
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Can I use OR statements in Java switches?
I have a switch statement. Is there a way to do an or statement within the switch. Ie
switch(val){
case 1
//Do Stuff
break;
case 2
//Do Stuff
break;
case 3
//Do Stuff
break
}
Instead do something like
switch(val){
case 1 or 3
//Do Stuff
break;
case 2
//Do Stuff
break;
}
Yes, try this:
switch(val){
case 1: case 3:
//Do Stuff
break;
case 2:
//Do Stuff
break;
default:
//Do Stuff
break;
}
Always remember to include the default case too.
switch(val) {
case 1:
case 3:
//Do Stuff
break;
case 2
//Do Stuff
break;
}
switch(val) {
case 1:
case 2:
//Do Stuff
break;
case 3:
//Do Stuff
break;
}
Yes:
switch(val){
case 1:
case 2:
//Do Stuff
break;
case 3:
//Do Stuff
break;
default:
break;
}
Ok here I have a switch case statement which is falling through and trying every option. Basically I want something that if the user enters the letter A in the textbox the background will change to b! if they dont enter the letter A then I want it to stop executing the code. But what has been happening is if the user enters lets say for example the letter Q when the background is letter A then the background will change to letter R instead of telling the user that they are wrong. basically I would like to know how I can stop the background from changing if the user does not enter the letter they are on here is the code.
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
switch(ch - 'A') {
case 0:
//A;
gestureViewer.setBackgroundResource(R.drawable.lettersb);
break;
case 1:
gestureViewer.setBackgroundResource(R.drawable.lettersc);
break;
case 2:
gestureViewer.setBackgroundResource(R.drawable.lettersd);
break;
case 3:
gestureViewer.setBackgroundResource(R.drawable.letterse);
break;
case 4:
gestureViewer.setBackgroundResource(R.drawable.lettersf);
break;
case 5:
gestureViewer.setBackgroundResource(R.drawable.lettersg);
break;
case 6:
gestureViewer.setBackgroundResource(R.drawable.lettersh);
break;
case 7:
gestureViewer.setBackgroundResource(R.drawable.lettersi);
break;
case 8:
gestureViewer.setBackgroundResource(R.drawable.lettersj);
break;
case 9:
gestureViewer.setBackgroundResource(R.drawable.lettersk);
break;
case 10:
gestureViewer.setBackgroundResource(R.drawable.lettersl);
break;
case 11:
gestureViewer.setBackgroundResource(R.drawable.lettersm);
break;
case 12:
gestureViewer.setBackgroundResource(R.drawable.lettersn);
break;
case 13:
gestureViewer.setBackgroundResource(R.drawable.letterso);
break;
case 14:
gestureViewer.setBackgroundResource(R.drawable.lettersp);
break;
case 15:
gestureViewer.setBackgroundResource(R.drawable.lettersq);
break;
case 16:
gestureViewer.setBackgroundResource(R.drawable.lettersr);
break;
case 17:
gestureViewer.setBackgroundResource(R.drawable.letterss);
break;
case 19:
gestureViewer.setBackgroundResource(R.drawable.letterst);
break;
case 20:
gestureViewer.setBackgroundResource(R.drawable.lettersu);
break;
case 21:
gestureViewer.setBackgroundResource(R.drawable.lettersv);
break;
case 22:
gestureViewer.setBackgroundResource(R.drawable.lettersw);
break;
case 23:
gestureViewer.setBackgroundResource(R.drawable.lettersx);
break;
case 24:
gestureViewer.setBackgroundResource(R.drawable.lettersy);
break;
case 25:
gestureViewer.setBackgroundResource(R.drawable.lettersz);
break;
would it be better if I set the pictures in an array and then went from there? Ive tried including If switch case, but it didnt work at all....
I'd pre-populae an array and invoke:
gestureViewer.setBackgroundResource(myArray[ch - 'A']);
It will make your code much more readable.
You can also do it with a Map<Character,MyImage> - it might allow you to add more features easily in the future.
If you do that, invokation will be using
gestureViewer.setBackgroundResource(myMap.get(ch));
Note that the array/map needs to be populated only once in the application's runtime.
You could, for example, put all the R.drawable.abc inside an Array and then address its index.
int[] bgImg = {R.drawable.a, ... , R.drawable.z}
char ch = words.getText().toString().toUpperCase().charAt(0);
int index = ch - 'A';
if(index > 0 && index < bgImg.length){
gestureViewer.setBackgroundResource(bgImg[index]);
} else {
gestureViewer.setBackgroundResource(R.drawable.standardImage);
}
Also note, that I'm using toUpperCase() to make sure you can substract the capital 'A'
Try:
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
int id = getResources().getIdentifier("letters" + ch, "drawable", context.getPackageName())
gestureViewer.setBackgroundResource(id);
}
}
I'm looking to make a switch where 5 of the cases are functionally identical, but then there will be other unique cases. Is there a way to list a case value that handles 5 different values? Thanks
You can compound the labels in the switch
switch (variable) {
case 'a': case 'b' : case 'c' : case 'd' :
do something;
break;
case 'e': case 'f' :
do something else
break;
default:
do something;
}
Thinking of a switch as a jump to a label (possibly coupled with a jump (the break) to the end) will help. That means the switch
switch (variable) {
case 'a': case 'b' : case 'c' : case 'd' :
do something;
// note that there's no break here.
case 'e': case 'f' :
do something else
break;
default:
do something;
}
will "do something" and "do something else" for 'a', 'b', 'c', and 'd'; while it will only "do something else" for 'e' and 'f'. Finally if it's not any of the above it hits the default block of "do something".
switch (value) {
case 1:
case 2:
case 3:
case 4:
doSomethingIdentical();
break;
case 5:
doSomethingDifferent();
break;
default:
break;
}
This is very easy to do. Instead of just having one case value that handles all 5 different values, let the 5 case values fall through to each other, like so:
switch(value)
{
case 1:
case 2:
//case 1 and 2 will both result in this code being executed
doSomething();
break;
case 3:
doSomethingElse();
break;
}
As long as you don't put a break; on a switch it will fall through to the next statement.
In that way, you can have something like this:
String value(int val) {
String out = "";
switch(val) {
case 0:
out = "case 0";
break;
case 1:
out = "case 1";
break;
case 2:
case 3:
case 4:
case 5:
case 6:
out = "case 2, 3, 4, 5 or 6";
break;
case 7:
out = "case 7";
break;
}
return out;
}
Yes, just use a switch like this:
switch(v) {
case 1:
case 2:
case 3:
identicFunctionality();
break;
case 4:
other01();
break;
case 5:
other02();
break;
default:
_default();
}
As of Java 12 I believe it is supported. Check out JEP 354. I have never used the syntax but I think it would run like this for your case.
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("1-5");
case 7 -> System.out.println(7);
case 8 -> System.out.println(8);
case 9 -> System.out.println(9);
}
on a related note JEP 325 is also cool.