This question already has answers here:
Using switch statement with a range of value in each case?
(20 answers)
Closed 7 years ago.
Here is my code:
switch(age) {
case 10:
System.out.println("You are too young to drive.");
break;
case 20:
System.out.println("You can drive!");
break;
default:
System.out.println("Error");
}
What happens if the age is 15? Well, it gives me an error. So I was wondering if it's possible to include a condition within the case. For example,
case (age>=10 && age<=20):
System.out.println("You're still too young to drive...");
break;
I could use an if statement, but I'm wondering if this is possible with a switch.
case Requires a Constant Expression
No. It's not possible because a case must be a constant expression. But you could (as you guessed) use an if. Logically, anyone under 20 (assuming that's the legal age) is too young to drive.
final int drivingAge = 20;
if (age < drivingAge) {
System.out.printf("%d is too young to drive...%n", age);
} else {
System.out.printf("%d is old enough to drive.%n", age);
}
Alternatively
That could be written with ? : conditional operator (aka a ternary expression; note some people find the ternary difficult to read) like
final int drivingAge = 20;
System.out.printf(age < drivingAge ? "%d is too young to drive...%n"
: "%d is old enough to drive.%n", age);
Because of fall-through you can do this:
switch(age){
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
System.out.println("You are too young to drive.");
break;
case 20:
System.out.println("You can drive!");
break;
default:
System.out.println("Error");
}
It is a little more code but it accomplishes the same thing.
No, in Java you cannot do it. Use if statement instead. Constructs similar to what you want exist in other languages like Scala.
You can't do this in Java. A switch jumps to the case that matches the value you're switching on. You can't use expressions of age inside the case. However, you can use something called a "fallthrough" (see here and search for "fall through").
So, for your example, you could do something like:
switch(age)
{
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
System.out.println("You are too young to drive.");
break;
case 20:
case 21:
System.out.println("You can drive!");
break;
default:
System.out.println("Error");
}
However, your problem is best solved with an if.
Sadly, it's not possible in Java. You'll have to resort to using if-else statements.You can try this, which is very repetitive.
switch(age){
case 10: case 11: case 12: case 13: case 14: case 15:
//And So on
System.out.println("You are too young to drive.");
break;
case 20:
System.out.println("You can drive!");
break;
default:
System.out.println("Error");
}
Try if statement
public void canDrive(int age){
if(age <= 19){
System.out.println("You are too young to drive.")
}
else{
System.out.println("You can drive!");}
}
Related
I have an integer array filled with values 0-51.
0-12
ranks 2-10JQKA of suit Spades
13-25
ranks 2-10JQKA of suit Hearts
26-38
ranks 2-10JQKA of suit Clubs
39-51
ranks 2-10JQKA of suit Diamonds
I need to find a way to use division in order to obtain the suit, and modulo for the rank. NOTE: I would appreciate ideas, not answers, as I need some help getting started.
My current code consists of an if/switch statement structure. However I'm looking for a way to implement the above requirements.
if(card <= 12) {
switch(card) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
System.out.println(card + " of Spades");
break;
case 9:
System.out.println("Jack of Spades");
break;
case 10:
System.out.println("Queen of Spades");
break;
case 11:
System.out.println("King of Spades");
break;
case 12:
System.out.println("Ace of Spades");
break;
}
}
You are right, to obtain the suit you can use div.
Lets say that card is in range [0-51].
suit = card div 13
To obtain the value within suite (value is in range [0-12]) you can use the formula
value = card mod 13
I want to use the switch statement in some simple code i'm writing.
I'm trying to compare the variable in the parenthesis with values either < 13 or >= 13.
Is this possible using Switch?
var age = prompt("Enter you age");
switch (age) {
case <13:
alert("You must be 13 or older to play");
break;
case >=13:
alert("You are old enough to play");
break;
}
Directly it's not possible but indirectly you can do this
Try like this
switch (true) {
case (age < 13):
alert("You must be 13 or older to play");
break;
case (age >= 13):
alert("You are old enough to play");
break;
}
Here switch will always try to find true value. the case which will return first true it'll switch to that.
Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.
Instead of switch you can easily to the same thing if else right?
if(age<13)
alert("You must be 13 or older to play");
else
alert("You are old enough to play");
This worked in my case:
var enteredAge = prompt("Enter your age");
let ageMoreThan13 = parseInt(enteredAge) >= 13;
let ageLessThan13 = parseInt(enteredAge) < 13;
switch (ageMoreThan13 || ageLessThan13) {
case ageLessThan13:
alert("You must be 13 or older to play");
break;
case ageMoreThan13:
alert("You are old enough to play");
break;
}
Instead of switch use nested if else like this:
if (x > 10) {
disp ('x is greater than 10')
}
else if (x < 10){
disp ('x is less than 10')
}
else
{
disp ('error')
}
You may use a conditional (ternary) operator instead. It takes a condition followed by a question mark (?), then an expression to execute if the condition is true and another if it is false.
This operator is frequently used as a shortcut for the if statement.
age >= 13 ? "You are old enough to play" : "You must be 13 or older to play";
It might be a bit silly to do this with a switch-case, but I added an answer where using switch-case, just for completeness.
var age = prompt("Enter you age");
switch (age) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
alert("You must be 13 or older to play");
break;
default:
alert("You are old enough to play");
break;
}
I have an Excel file, which I am reading using Apache POI APIs; which gives me control over cells/columns in my Excel.
I have around 17 columns in my Excel and these are with different datatypes. I want to populate a model object from these column values. So, I came up with something like below to populate my model object:
private WHTApps populateModel(int columnIndex, Object cellValue) {
WHTApps whtApp = new WHTApps();
switch (columnIndex) {
case 0:
whtApp.setVendorCode((int) cellValue);
break;
case 1:
whtApp.setVendorName((String) cellValue);
break;
case 2:
whtApp.setCountry((String) cellValue);
break;
case 3:
whtApp.setApplicationReceivedFromUSDate((Date) cellValue);
break;
case 4:
whtApp.setContractNumber((String) cellValue);
break;
case 5:
whtApp.setContractEffectiveDate((Date) cellValue);
break;
case 6:
whtApp.setContractExpirationDate((Date) cellValue);
break;
case 7:
whtApp.setAutomaticRenewal((String) cellValue);
break;
case 8:
whtApp.setReducedRate((int) cellValue);
break;
case 9:
whtApp.setForm17((String) cellValue);
break;
case 10:
whtApp.setResidencyCertIssueDate((Date) cellValue);
break;
case 11:
whtApp.setTaxAuthoritySubmissionDate((Date) cellValue);
break;
case 12:
whtApp.setTaxAuthorityAcceptanceDate((Date) cellValue);
break;
case 13:
whtApp.setStatus((String) cellValue);
break;
case 14:
whtApp.setForm17Expiration((Date) cellValue);
break;
case 15:
whtApp.setComments((String) cellValue);
break;
case 16:
whtApp.setRemarks((String) cellValue);
break;
case 17:
whtApp.setCategory((String) cellValue);
break;
default:
}
return whtApp;
}
But, this gives rise to a really high cyclomatic complexity value of 19.
Now how do I reduce the cyclomatic complexity as I have 17 columns which I need to populate in my model object?
Thanks for helping me out
Akshay
I just run over something strange in my java code:
switch (result) {
case 0:
result_amount = 500;
case 1:
result_amount = 600;
case -1:
result_amount = 700;
}
result is from primitive type int.
For value 1 case 1 and case -1 are executed.
Is this a normal switch case behaviour? If yes: why?
You need to use the break keyword after a case block:
switch (result) {
case 0:
result_amount = all_amounts[i];
break;
case 1:
result_amount = all_amounts[i];
break;
case -1:
result_amount = all_amounts[i+1];
}
The switch statement will make a jump to the correct case tag, then execute all the code that follow, ignoring potential other case tags. You can consider the switch statement just like a goto one.
Fall Through.
quoting from 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.
You have to add the break after each case.
case 1:
result_amount = 600;
break;
Remember:
This is a mistake that almost every beginner will make. That's why I like C# more. It doesn't allow "fall-through".
What you did wrong is you fell-through the switch statement. Try using 0 as the value of result. It will go through all the cases. When a switch case finishes execution, the next case gets executed. That's why we need to add a break; statement for each case of the switch statement.
switch (result) {
case 0:
result_amount = 500;
break;
case 1:
result_amount = 600;
break;
case -1:
result_amount = 700;
break;
}
But sometimes we want fall-through. For example when we want to calculate number of days in a month:
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
days = 28;
case 4:
case 6:
//Lots of code...
}
Without break statement next cases will be executed.
Generally Case Label Should be Integer / Constant
Negative numbers having no decimal point are also considered as Integer
Thus it is not necessary to have Case Labels greater than Zero
This is fall through condition.
switch (result) {
case 0:
result_amount = all_amounts[i];
case 1:
result_amount = all_amounts[i];
case -1:
result_amount = all_amounts[i+1];
}
To avoid it you must put break statement
switch (result) {
case 0:
result_amount = all_amounts[i];
break;
case 1:
result_amount = all_amounts[i];
break;
case -1:
result_amount = all_amounts[i+1];
break;
}
Now only matching case will be executed.
You should include break and default to run program in a proper way. Let me give you a example of it.
switch (result) {
case 0:
result_amount = 500;
break;
case 1:
result_amount = 600;
break;
case -1:
result_amount = 700;
break;
}
I have a switch case in Java like this:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
/** For int more than 2, then I need
for it to do something same.
*/
case 3://Do different and case6
break;
case 4://Do different and case6
break;
case 5://Do different and case6
break;
case 6:
break;
}
What is an elegant way to do this, sans having a special case 6 function that case 3-5 calls? (I use int here, but that is an example, so I can't use if(int >2))
A switch can't really do exactly what you are asking out of the box. You can construct something like this with a nested switch though:
outer_switch: switch (example) {
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default: {
switch (example) {
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
case 5: System.out.println("5");
break;
case 6: System.out.println("6");
break;
default: break outer_switch;
}
System.out.println("not 1 nor 2");
}
}
Note the labeled break on outer_switch which is a way to circumvent the shared code if example does not meet any of the inner cases.
One way I could think of is to move your code to different functions. Something like this.
void case1(){
// do something
}
...
void case3(){
// do something
case6();
}
...
void case6(){
// do something
}
// This switch is in some other method.
switch(int example)
{
case 1: //Do different
case1();
break;
...
case 3://Do different and case6
case3(); //internally calls case 6
break;
...
case 6:
case6();
break;
}
Or you can even have different methods for each case and call case3() and case6() methods in the case 3:. Either way, the methods solutions would work, and IMHO, it would be a bit more elegant and multiple switch statements.
I'm not sure if it's elegant, but one way would be to have two switch blocks:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
case 3:
// Do whatever
break;
case 4:
// Do whatever
break;
case 5:
// Do whatever
break;
}
switch(int example)
{
case 3:
case 4:
case 5:
case 6:
// Do whatever (case 3-5 fall through)
break;
}
Although your code is not pretty it's probably going to give you decent performance. Your other obvious option is an if-elseif-else statement. See the accepted answer here for why switch might be the best option, and here to see what performance issues you might run into with large switch statements in Java.
This might also be a solution to what you want to achieve:
switch(example){
case 1:
System.out.println(example);
break;
case 2:
System.out.println(example);
break;
case 3:
System.out.println("I'm case 3");
case 4:
if (example == 4){
System.out.println("I'm case 4");
}
case 5:
if (example == 5){
System.out.println("I'm case 5");
}
case 6:
System.out.println("I'm in extra case " + example);
break;
}
The idea is that you add an extra condition check to let your code fall through all the branches without executing unnecessary ones.