how do I use switch and case in a java game? - java

I'm making a game in Slick2D and I have a lot of 'if' statements and I want to get rid of that. Now this is my code:
if((playerPositionX>570 && playerPositionX<835) && (playerPositionY>16 && playerPositionY<260)){
g.setColor(Color.red);
g.drawString("Ready to play? press enter!", 400,350);
}
Everything is fine but I have like 8 and going up of these, obviously with different coordinates.
So I would like to know if it's possible to use a switch and case method to fix this.

You can't use a Switch with ranges as cases. In other words, something like this:
Switch(playerPosition)
case 570-835:
....
doesn't exist. You could do:
int num;
if (playerPositionX>570 && playerPositionX<835){
num = 0;
if (playerPositionX>836 && playerPositionX<1000){
num = 1;
and then
Switch(num){
case 0:
...
case 1:
...
but you'll still have to use the if statements.

Related

Proper Format for a Switch/Case in a Class

Good Evening,
I created this method for a class. I used a switch/case to execute depending on the value of expression. I included an if-else method for each case. I do get an error on case 1-> switch rules are a preview feature and are disabled by default. I attempted to add a : after case 1 and case 2but my results reached high numbers for the sets. I changed the : to -> and it worked appropriately. Now I am wondering if this was a proper way to set the case statements or should it be written differently.
private void playGame()
{
double winCheck = Math.random();
switch (matchServer) {
case 1 ->{
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
}
case 2 ->{
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
A correct switch statement must use ':'
Also, 'break' is missing. This to avoid executing next cases.
You can add 'default' that means that case 1 and case 2 were not presented.
switch (matchServer) {
case 1:
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
break;
case 2:
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
break;
default:
//If it was not 1 or 2
//Printing the values can help
}

Check in if is switch case choosen

How can i check if case (for example 3 ) was choosen to make continuation of story?
I wrote this in java and I would go full detail with story but i dont know how could i .I thought I could nest cases inside each other but if I can choose options(scanner.nextInt();) also add in them.I thought if statement would work better but i dont know how can i check it .I must add that didnt found any answers to this problem before posting.Thanks for reviewing and have a good day
int choice_1 = scanner.nextInt();
switch(choice_1)
{
case 1:
System.out.println("Guard: Its a honor to meet u sir.Its a pleasure to let You through \nBut do u have coin pass?");
if(pass==1){
ending();
}
else{"You should get coin pass first. I am sure that wont be a problem for Prince *laughs*"}
break;
case 2:
System.out.println("*Guard immediately avoided attack and attack u harder that u excepted");
playerHp = playerHp -30;
playerArmorHp = playerArmorHp - 50;
break;
case 3:
System.out.println("Guard : Goodbye Sir");
plan();
break;
default:
System.out.println("Guard is impatient of your not telling anything.Choose option before making him mad.\n"+line);
break;
}
if(switch ( case:3)){
System.out.println("Do u have coin pass?");
int pass = scanner.nextInt();
}
You could change your if clause to if(choice_1 == 3) to get what you want.

Can you use conditional statements in switch-case in Android?

I can't seem to find a straight forward yes or no to this in my searching. In Android, is there a way to use a conditional statement in case-switch? For example, with age being an int value:
switch (age){
case (>79):
// Do this stuff
break;
case (>50):
// Do this other stuff
break;
etc, etc
I've tried several ways to code this (completely shooting in the dark) and come up with compiler errors, and I've also tried a nested IF statement, but it doesn't support break so the logic breaks down and it ends up also executing ELSE code lower in the nesting. I feel like switch-case is my best bet but I can't find an example of the correct syntax for what I'm trying to do! Any help would be appreciated. All the examples I find just use switch-case for a few things like if it is a 1 do this, if it's a 2 do that, but without making 100 case statements to check against age, I'm not sure how else to work this.
No. You cannot do this,
switch (age){
case (>79):
// Do this stuff
break;
case (>50):
// Do this other stuff
break;
}
You need an if and else,
if (age > 79) {
// do this stuff.
} else if (age > 50) {
// do this other stuff.
} // ...
It is not possible. Instead, Try this minimalist approach
age > 79 ? first_case_method()
: age > 50 ? second_case_method()
: age > 40 ? third_case_method()
: age > 30 ? fourth_case_method()
: age > 20 ? fifth_case_method()
: ...
: default_case_method();
You can't do this use if then statement.
if(age > 79)
{
//do stuff
}
else if(age > 50)
{
//do stuff
}
else
{
/do stuff
}
etc...
If you are using a loop you might want to look at What is the "continue" keyword and how does it work in Java?. This is not a good place to use switch.
if(age > 79)
{
//do stuff
continue; // STOP FLOW HERE AND CONTINUE THE LOOP
}
else if(age > 50)
{
//do stuff
continue; // STOP FLOW HERE AND CONTINUE THE LOOP
}
each case of switch is supposed to be an integer or String since JavaSE 7 and you are trying to feed a boolean value to it so its not possible .Read oracle doc to know about java switch in detail
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You can't use conditional statements with switch.
But you CAN do it with if statements! If you have a loop you can use continue to stop any upcoming lines and start from the beginning of the innermost loop.
if(age>76){
// Code...
continue;
}else if(age>50){
// More Code...
continue;
}else{
// Even more code...
continue;
}
It can be done.
The code needs to be slightly altered.
public static void main(String[]arguments)
{
int x=1, age=55;
switch(x)
{
case 1: if((age>=60)&&(age<200))
System.out.println("Senior Citizen");
case 2: if((age>=18)&&(age<60))
System.out.println("Adult");
case 3: if((age>=12)&&(age<18))
System.out.println("Teenager");
break;
default :
System.out.println("Child");
break;
}
}

How to execute code based on integer value

I have an int, int minion1Hp, which can be a value of 0 -> 20. Depending on the value it is, a certain image resource will be set for an ImageView, using bar1.setImageResource(R.drawable.hpa);. However, my code currently looks like this:
if (minion1Hp == 0) {
bar1.setImageResource(R.drawable.hp);
}
if (minion1Hp == 1) {
bar1.setImageResource(R.drawable.hpa);
}
if (minion1Hp == 2) {
bar1.setImageResource(R.drawable.hpb);
}
if (minion1Hp == 3) {
bar1.setImageResource(R.drawable.hpc);
}
if (minion1Hp == 4) {
bar1.setImageResource(R.drawable.hpd);
}
if (minion1Hp == 5) {
bar1.setImageResource(R.drawable.hpe);
}
... and so on. Is there a more efficient way of doing this, rather than a long list of if statements?
Suggestion: initialize a map at startup (say in onCreate()). Like this:
mDrawables = new HashMap<Integer, Integer>();
mDrawables.put(0, R.drawable.hp);
mDrawables.put(1, R.drawable.hpa);
...
then just do:
bar1.setImageResource(mDrawables.get(minion1Hp));
You can use a switch statement with a separate case for each instance. On a side note, you shouldn't be using just if statements up there, your code will run slowly, you should be using else if to make it run faster (since your hp can never be 1 and 2 at the same time.
Ex for switch statements:
switch (minion1Hp){
case 1:
bar1.setImageResource(R.drawable.hp);
break;
case 2:
bar1.setImageResource(R.drawable.hpa);
break;
etc.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
An improvement here would be to change each if after the first one to an else if as minion1Hp can't be multiple values at the same time, but you might find it slightly neater to have the whole thing in a switch-case block instead.

Best way to format multiple 'or' conditions in an if statement

I have an if statement with many conditions (have to check for 10 or 15 constants to see if any of them are present.)
Instead of writing something like:
if (x == 12 || x == 16 || x == 19 || ...)
is there any way to format it like
if x is [12, 16, 19]?
Just wondering if there is an easier way to code this, any help appreciated.
The answers have been very helpful, but I was asked to add more detail by a few people, so I will do that to satiate their curiosity. I was making a date validation class that needed to make sure days were not > 30 in the months that have only 30 days (of which there are 4, I think) and I was writing an if statement to check things like this:
if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
I was just wondering if there was a faster way to code things like that - many of the answers below have helped.
I use this kind of pattern often. It's very compact:
Define a constant in your class:
private static final Set<Integer> VALUES = Set.of(12, 16, 19);
// Pre Java 9 use: VALUES = new HashSet<Integer>(Arrays.asList(12, 16, 19));
In your method:
if (VALUES.contains(x)) {
...
}
Set.of() returns a HashSet, which performs very well even for very large sets.
If performance is not important, you can code the gist of it into one line for less code footprint:
if (Set.of(12, 16, 19).contains(x))
but know that it will create a new Set every time it executes.
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like
if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)
Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become
switch(dispatchTable[x])
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}
Whether or not this is appropriate depends on the semantics of the problem.
If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
You could look for the presence of a map key or see if it's in a set.
Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
With Java 8, you could use a primitive stream:
if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
but this may have a slight overhead (or not), depending on the number of comparisons.
Here is another answer based on a comment above, but simpler:
List numbers= Arrays.asList(1,2,3,4,5);
if(numbers.contains(x)){
//
}

Categories