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
Related
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;
}
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!");}
}
I'm using switch case in Java for the first time and I'm a bit unsure about the syntax. Assuming the setTeamName function works, which it does, would the following function make all of the teams in my array have the placeholder String as it's name or should I from case 0: since i starts at 0?
public static Team[] makeTeams(){
Team[] teams = new Team[10];
for(int i = 0; i < teams.length; i++){
switch(i){
case 1: teams[0].setTeamName("Arsenal");
case 2: teams[1].setTeamName("Arsenal");
case 3: teams[2].setTeamName("Arsenal");
case 4: teams[3].setTeamName("Arsenal");
case 5: teams[4].setTeamName("Arsenal");
case 6: teams[5].setTeamName("Arsenal");
case 7: teams[6].setTeamName("Arsenal");
case 8: teams[7].setTeamName("Arsenal");
case 9: teams[8].setTeamName("Arsenal");
case 10: teams[9].setTeamName("Arsenal");
}
}
return teams;
}
use break Statement after every instruction in case.
Your case statements would need to start from 0, because as you rightly observe, i starts at zero. However, this appears to be the least of your problems (unless this is just an exercise in using switch case).
You don't need switch case in this situation at all. Plus, you never create any objects in the array, so every time you attempt to access the array at a particular index, you're going to get a null reference exception. The following will suffice:
Team[] teams = new Team[10];
for (int i = 0; i < teams.length; i++) {
teams[i] = new Team();
teams[i].setTeamName("Arsenal");
}
What you've effectively got in your original example is an example of an anti-pattern, the Loop-switch sequence. If you want the original example to work properly using this anti-pattern (for educational purposes only), you need to add break; statements to ensure that your case statements don't fall through:
Team[] teams = new Team[10];
for (int i = 0; i < teams.length; i++) {
teams[i] = new Team();
switch (i) {
case 0: teams[0].setTeamName("Arsenal"); break;
case 1: teams[1].setTeamName("Arsenal"); break;
case 2: teams[2].setTeamName("Arsenal"); break;
case 3: teams[3].setTeamName("Arsenal"); break;
case 4: teams[4].setTeamName("Arsenal"); break;
case 5: teams[5].setTeamName("Arsenal"); break;
case 6: teams[6].setTeamName("Arsenal"); break;
case 7: teams[7].setTeamName("Arsenal"); break;
case 8: teams[8].setTeamName("Arsenal"); break;
case 9: teams[9].setTeamName("Arsenal"); break;
}
}
Without the breaks, every case statement under the one that matches i is evaluated, e.g. when i == 0, all of the case statements will be executed.
You do have options in filling up the array but if your task requires you to use only switch then start with case 0 instead of 1, since 0 is the "first" case you are encountering.
Do you really need switch here? for loop will be enough.
Switch just move execution to case row and ignore another case for next time. So when you give i = 1 to switch all of the case statement will be executed. You can prevent it by using break;
switch (i) {
case 1:
teams[0].setTeamName("Arsenal");
break;
case 2:
teams[1].setTeamName("Arsenal");
break;
}
You are doing a lot of unnecessary work. Try
public static Team[] makeTeams(){
Team[] teams = new Team[10];
for(int i = 0; i < teams.length; i++){
teams[i] = new Team();
teams[i].setTeamName("Arsenal");
}
return teams;
}
You have few errors in your code:
1) You do not have case 0 - so it is not used. Suggestion is always use default case.
2) Each case should be finished with break; Otherwise all cases below are executed too. For example for case 9 these cases are called 9 and 10. and for case 1 all 10 cases have been called. (but for case 0 in your code none is called).
3) You had reserved array of 10 teams but you did not populated objects to this array. You code will produce null pointer exception.
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.
I'm wondering if I can use or in switch-case in Java?
Example
switch (value)
{
case 0:
do();
break;
case 2 OR 3
do2();
break;
}
There is no "or" operator in the case expressions in the Java language. You can however let one case "fall through" to another by omitting the break statement:
switch (value)
{
case 0:
do();
break;
case 2: // fall through
case 3:
do2();
break;
}