This question already has answers here:
Using switch statement with a range of value in each case?
(20 answers)
Closed 7 years ago.
I want to compare array length with some int values. I can do it with if else but how to do it with switch because switch is fast and I want to use that in my project
switch (array.length) {
case array.length <= 11: // how to do this
break;
default:
break;
}
With if else I can do this:
if (array.length <= 5) {
//my is code here
}
else if (array.length <= 15) {
//my is code here
}
else if (array.length <= 10) {
//my is code here
}
You can't. switch can only test exact values.
You could do:
switch(array.length) {
case 0: case 1: case 2: case 3:
case 4: case 5: case 6: case 7:
case 8: case 9: case 10: case 11:
// do stuff
break;
default:
break;
}
But why do you want to do this? What makes you think it's faster?
switch is not the same as if (...) { ... } else { ... }. You can only use == within a case. You would have to do something like this:
int length = array.length;
switch (length) {
case 0:
case 1:
case 2:
[...]
case 11:
// your code here
break;
//other cases here
}
Notice the missing break-statements, they are quite important.
I would recommend this tutorial for more details.
You can't do it(as per your example) using switch. Since the values of case are constant expression (case *value*).
Switch statements operate by exact matches rather than comparisons like if does. You can do what you want by introducing a new variable like this:
int value = (array.length <= 11 ? 0 : (array.length <= 20 ? 1 : 2));
switch (value) {
case 0: // 11 or under
break;
case 1: // 12 to 20
break;
case 2: // 21 or more
break;
}
I don't know if this buys you much over if/else statements, but if you find it cleaner to code, you can do it.
In your if/elseif, the if(array.length<=10) will never run because if(array.length<=15) is checked above it.
Doing this with an if/elseif structure would require less lines of code.
If you want to do this using a switch/case statement, this would work:
int length = array.length;
switch(length) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5: {
System.out.println("Case 0<=length<=5 triggered.");
break;
}
case 6:
case 7:
case 8:
case 9:
case 10: {
System.out.println("Case 6<=length<=10 triggered.");
break;
}
case 11:
case 12:
case 13:
case 14:
case 15: {
System.out.println("Case 10<=length<=15 triggered.");
break;
}
default: {
System.out.println("Default case triggered.");
}
}
Related
This question already has answers here:
In a switch statement, why are all the cases being executed?
(8 answers)
Closed last year.
I am working on the game where the columns of the board are represented by the characters but i would like to assign them an index.
I have decided to use the switch statement in that case, however it does produce the wrong result.
With the current code I attach, it gives me 14 as an index, however since the string is 7h, and it takes h as a char, it should give an index of 7. What Could be an issue? Thanks in advance!
public class Check {
public int columnToInt(char c) {
int index=0;
switch(c) {
case 'a':
index=0;
case 'b':
index=1;
case 'c':
index=2;
case 'd':
index=3;
case 'e':
index=4;
case 'f':
index=5;
case 'g':
index=6;
case 'h':
index=7;
case 'i':
index=8;
case 'j':
index=9;
case 'k':
index=10;
case 'l':
index=11;
case 'm':
index=12;
case 'n':
index=13;
case 'o':
index=14;
}
return index;
}
public static void main(String[] args) {
String myStr = "7h";
char c =myStr.charAt(1);
System.out.println("the char at position 1 is "+c);
Check check = new Check();
int result = check.columnToInt(c);
System.out.println(result);
}
}
Java switch statements can be a bit annoying to use. You need to use break or all the cases after the expected one will be executed as well.
switch(c) {
case 'a':
index=0;
break;
Alternatively you can use a return.
switch(c) {
case 'a':
return 0;
You must add the break keyword for each case.
For example:
case 'a':
index=0;
break;
otherwise next assignments are applied.
I am working to make a Advent Calendar for Christmas and needed to use a switch statement. My biggest dilemma is the fact that each (daysAway) case opens a new class designed for that day in particular. I am working off of what Google and Stack overflow can provide. I was wondering if there was any other way to compact this?
public void onClick(View v) {
//Calculate the days between (date - 12/7/20)
LocalDate dateBefore = java.time.LocalDate.now();
LocalDate dateAfter = LocalDate.of(2020, Month.DECEMBER, 25);
int daysAway = (int) ChronoUnit.DAYS.between(dateBefore, dateAfter);
switch(daysAway){
case 24:
openDay1();
break;
case 23:
openDay2();
break;
case 22:
openDay3;
break;
case 21:
openDay4;
break;
case 20:
openDay5;
break;
case 19:
openDay6;
break;
case 18:
openDay7;
break;
case 17:
openDay8;
break;
case 16:
openDay9;
break;
case 15:
openDay10;
break;
case 14:
openDay11;
break;
case 13:
openDay12;
break;
case 12:
openDay13;
break;
case 11:
openDay14;
break;
case 10:
openDay15;
break;
case 9:
openDay16;
break;
case 8:
openDay17;
break;
case 7:
openDay18;
break;
case 6:
openDay19;
break;
case 5:
openDay20;
break;
case 4:
openDay21;
break;
case 3:
openDay22;
break;
case 2:
openDay23;
break;
case 1:
openDay24;
break;
case 0:
openChristmas;
break;
default:
notTime.start();
break;
}
}
I know it is a giant mess and that is what I am trying to fix!
I appreciate any feedback you can give!
Use Java 14 switch expression syntax:
switch (daysAway) {
case 24 -> openDay1();
case 23 -> openDay2();
case 22 -> openDay3();
case 21 -> openDay4();
// ...
case 4 -> openDay21();
case 3 -> openDay22();
case 2 -> openDay23();
case 1 -> openDay24();
case 0 -> openChristmas();
default -> notTime.start();
}
Since the code is very simple, just collapse it on one line:
switch (daysAway) {
case 24: openDay1(); break;
case 23: openDay2(); break;
case 22: openDay3(); break;
case 21: openDay4(); break;
// ...
case 4: openDay21(); break;
case 3: openDay22(); break;
case 2: openDay23(); break;
case 1: openDay24(); break;
case 0: openChristmas(); break;
default: notTime.start();
}
Use an array of Java 8 method references (notice reversed order):
Runnable[] OPEN_METHODS = {
this::openChristmas,
this::openDay24,
this::openDay23,
this::openDay22,
this::openDay21,
// ...
this::openDay4,
this::openDay3,
this::openDay2,
this::openDay1
};
if (daysAway >= 0 && daysAway <= 24) {
OPEN_METHODS[daysAway].run();
} else {
notTime.start();
}
Since you said that "each (daysAway) case opens a new class designed for that day", use an interface (e.g. Runnable) and an array of class literals:
Class<?>[] OPEN_CLASSES = {
OpenChristmas.class,
OpenDay24.class,
OpenDay23.class,
OpenDay22.class,
OpenDay21.class,
// ...
OpenDay4.class,
OpenDay3.class,
OpenDay2.class,
OpenDay1.class
};
if (daysAway < 0 || daysAway > 24) {
notTime.start();
} else {
Runnable clazz;
try {
clazz = (Runnable) OPEN_CLASSES[daysAway].getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new AssertionError("Oops: " + e, e);
}
clazz.run();
}
You can also build the class name dynamically (no array or switch statement):
if (daysAway < 0 || daysAway > 24) {
notTime.start();
} else {
String className = (daysAway == 0 ? "OpenChristmas" : "OpenDay" + (25 - daysAway));
Runnable clazz;
try {
clazz = (Runnable) Class.forName(className).getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new AssertionError("Oops: " + e, e);
}
clazz.run();
}
if (daysAway > 0)
openDay(25-daysAway); // you haven't shown what you would do here,
// but presumably you don't need to write 24 separate functions
else
notTime.start();
I have set up a console menu like so:
int userOption = printMenu(sc);
while(userOption != 6){
switch(userOption) {
case 1: //function 1
break;
case 2: //function 2
break;
case 3: //function 3
break;
case 4: //function 4
break;
case 5: //function 5
break;
case 6: //
break
default: //statement asking for valid option
}
}
However when I run this, it only allows me to carry out the method I want to properly once and then rather than return to my menu and allow me to continue using other functions on top of the one I have just used, it just keeps repeating the original function I used.
Can anybody help me out and give me some advice?
From what is given here you seem to not get another userinput. To solve it you need to get another userinput after executing the loop.
int userOption = printMenu(sc);
while(userOption != 6) {
switch(userOption) {
case 1: //function 1
break;
case 2: //function 2
break;
case 3: //function 3
break;
case 4: //function 4
break;
case 5: //function 5
break;
case 6: //
break
default: //statement asking for valid option
}
userOption = printMenu(sc);
};
As a little additon:
To save yourself the double input you could simply rewrite the loop to a do while loop:
int userOption = 0;
do {
userOption = printMenu(sc);
switch(userOption) {
case 1: //function 1
break;
case 2: //function 2
break;
case 3: //function 3
break;
case 4: //function 4
break;
case 5: //function 5
break;
case 6: //
break
default: //statement asking for valid option
}
} while(userOption != 6);
adding to your comment, you might not store the value into userOption again, but just ask for the input.
I am trying to do the following for a Java switch method with a series of JUnit Asserts but am stuck on using "less than" and "greater than" for two cases (see string/int error below), and am not sure how to use the ">" and "<" in my cases.
Here is the exercise followed by my code, followed by the error.
/*
Create a method which uses a switch statement to return a String representing the int passed in as a parameter to the method:
• given 1 return "One"
• given 2 return "Two"
• given 3 return "Three"
• given 4 return "Four"
• given an integer > 4, return "Too big"
• given an integer < 1, return "Too small"
*/
#Test
public void switchIntExample() {
assertEquals("One", stringRepInt(1));
assertEquals("Two", stringRepInt(2));
assertEquals("Three", stringRepInt(3));
assertEquals("Four", stringRepInt(4));
assertEquals("Too big.", stringRepInt(>4));
// assertEquals("Too small.", stringRepInt(<4));
}
//Switch statement for above:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
//TODO: question on how to do LESS THAN and GREATER THAN:
// error line:
case (numVar > 4):
numVar = "Too big.";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
ERROR:
Error:(293, 27) java: bad operand types for binary operator '>'
first type: java.lang.String
second type: int
case statements only support constant expressions (you cannot do less than, or greater than, in a case and you can't test numVar - the String - with less than). You can use an if and something like
public String stringRepInt(int numberSize) {
String numVar = null;
if (numberSize > 4) {
numVar = "Too big.";
} else {
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
You should add it to the default section, so like this:
default:
numVar = "Too Big";
break;
The purpose of the default section is to deal with all cases not dealt with by the switch cases. You should be taking advantage of that (as #GreenMatt and #FredK mentioned in comments) by putting the 'if checks' in the default section, as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
break;
}
System.out.println(numVar);
return numVar;
}
Further, you could add else if (numberSize < 1) numVar = "Too small"; under the if statement if you want to check for number's smallest than one. This is also important because it prevents your method from returning null. (Which currently happens if the user enters a value less than 1)
The resulting code is as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
else
numVar = "Too small";
break;
}
System.out.println(numVar);
return numVar;
}
In the error line you are comparing String and int.
error line: case (numVar > 4): numVar = "Too big."; break;
you have declared numVar as String and comparing that with int value 4. Please correct that or I think you are trying to compare numberSize with value 4. Convert that String to int and compare it.
I'm trying to create a switch statement that takes the month in as an integer, and based on that integer, I'd like to output a month name. For some reason that I don't know, the case '10' gives me an Invalid character constant error message. Does anyone know why this is happening and how I can solve this? Thanks, the code is below:
switch (month) {
case '1': System.out.println("January");
break;
case '2': System.out.println("February");
break;
case '3': System.out.println("March");
break;
case '4': System.out.println("April");
break;
case '5': System.out.println("May");
break;
case '6': System.out.println("June");
break;
case '7': System.out.println("July");
break;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;
}
After answer:
switch (month) {
case "1": System.out.println("January");
break;
case "2": System.out.println("February");
break;
case "3": System.out.println("March");
break;
case "4": System.out.println("April");
break;
case "5": System.out.println("May");
break;
case "6": System.out.println("June");
break;
case "7": System.out.println("July");
break;
case "8": System.out.println("August");
break;
case "9": System.out.println("September");
break;
case "10": System.out.println("October");
break;
case "11": System.out.println("November");
break;
case "12": System.out.println("December");
break;
}
after more answers:
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
case 7: System.out.println("July");
break;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
}
'10' has two characters, i.e. a '1' and a '0'
Why don't you just use int instead of char for you switch statement variable...
int month = // ... however you get your month
switch(month) {
case 1: // ...
case 2: // ...
case 3: // ...
// ...
}
In Java `` denotes a character whereas "" denotes a string. 10 is not a character in Java but two characters therefore you cannot place it there.
In Java 7 you can do a switch on Strings so you'd have to change all your `` to "" and month to a String like this:
switch(month) {
case "1": // stuff
/* rest */
}
Or drop the `` altogether and switch on int:
switch(month) {
case 1: // stuff
/* rest */
}
As said by others '10' has 2 characters . Why don't you use integers instead :
int month;
switch(month){
case 1:
break;
.
.
.
}
From java 1.7 Strings are also allowed in switch statements so you can also write :
String month = // i/p
switch(month){
case "1" :
break;
.
.
.
.
.
}
You are having 2 characters after the 9
e.g. 10, 11, 12
So that can't be consider as a single char. That is why you are getting the error.
If you are using Java version 1.7 or above you can use string instead of char. But I think the best way is to cast month variable to a int and have int cases
//first cast month to a int
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
......
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
}
If you make month as integer, then remove single quotes and it will work
else make month as string it will work.