Reputation: 45
Hopefully you can see what I am going for here. Obviously this code doesn't work but I'm basically trying to say if the random number is one of these values, run this code. If the random number is another value run that code. I need something that is equivalent to a big or statement without using a large if-else. Thanks
static int cardNumber = rnd.nextInt(13) + 1;
if (cardNumber == 1||11||12||13)
{
System.out.println(faceCard + " of " + suit);
}
else
{
System.out.println(cardNumber + " of " + suit);
}
Upvotes: 2
Views: 137
Reputation: 81
You could use a switch case with a fallthrough.
public static void main(String args[]) {
int cardNumber = 10;
switch (cardNumber) {
case 1:
case 11:
case 12:
case 13:
// your if case
break;
case 100:
// some other case (example)
break;
default:
// else case
break;
}
}
You could also write a method which tells you if a card has a face! This would be a lot easier to use and would prevent redundant code.
Also you could the class card, instead of an integer to save your card value. An Enum wouldn't be bad either.
class Card {
public static boolean hasFace(int cardNum) {
if (cardNum > 13)
throw new InvalidParameterException("There is no card with a value greater 31!");
boolean rval = false;
switch (cardNum) {
case 1:
case 11:
case 12:
case 13:
rval = true;
break;
default:
break;
}
return rval;
}
}
Main for case 2:
public static void main(String args[]) {
int cardNumber = 10;
if(Card.hasFace(cardNumber)){
// your if case
}
else {
// your else case
}
}
Upvotes: 0
Reputation: 968
You could just simplify it I suppose, in your case specifically this might work..
int cn = rnd.nextInt(13) + 1;
if(cn <= 10 && cn > 1) {
System.out.println("Non-Face");
} else {
System.out.println("Face");
}
Upvotes: 0
Reputation: 1074495
Well, it's not a large if/else, it's just two conditions:
static int cardNumber = rnd.nextInt(13) + 1;
if (cardNumber == 1 || cardNumber >= 11)
{
System.out.println(faceCard + " of " + suit);
}
else
{
System.out.println(cardNumber + " of " + suit);
}
Upvotes: 1
Reputation: 26961
Use a switch(int)
to clarify
static int cardNumber = rnd.nextInt(13) + 1;
switch (cardNumber)
case 1:
case 11:
case 12:
case 13:
System.out.println(faceCard + " of " + suit);
break;
default:
System.out.println(cardNumber + " of " + suit);
break;
}
Upvotes: 1
Reputation: 24812
You could benefit from a switch / case :
switch (caseNumber) {
case 1 : case 11 : case 12 : case 13 :
<specific case code>;
break;
default :
<general case code>;
break;
}
Upvotes: 5