Java 如果返回一个特定的随机数,需要比大量if-else更好的东西吗
希望你能明白我的目的。显然,这段代码不起作用,但我基本上是想说,如果随机数是这些值之一,请运行这段代码。如果随机数是另一个值,则运行该代码。我需要的东西,是相当于一个大的或声明,而不使用一个大的如果其他。谢谢Java 如果返回一个特定的随机数,需要比大量if-else更好的东西吗,java,if-statement,random,Java,If Statement,Random,希望你能明白我的目的。显然,这段代码不起作用,但我基本上是想说,如果随机数是这些值之一,请运行这段代码。如果随机数是另一个值,则运行该代码。我需要的东西,是相当于一个大的或声明,而不使用一个大的如果其他。谢谢 static int cardNumber = rnd.nextInt(13) + 1; if (cardNumber == 1||11||12||13) { System.out.println(faceCard + " of " + suit); } else {
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);
}
您可以从交换机/机箱中获益:
switch (caseNumber) {
case 1 : case 11 : case 12 : case 13 :
<specific case code>;
break;
default :
<general case code>;
break;
}
开关(箱号){
案例1:案例11:案例12:案例13:
;
打破
违约:
;
打破
}
使用开关(int)
进行澄清
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;
}
好吧,这不是一个很大的if/else,它只是两个条件:
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);
}
我想你可以把它简化一下,在你的情况下,这可能行得通
int cn = rnd.nextInt(13) + 1;
if(cn <= 10 && cn > 1) {
System.out.println("Non-Face");
} else {
System.out.println("Face");
}
int cn=rnd.nextInt(13)+1;
如果(cn 1){
系统输出打印项次(“非正面”);
}否则{
系统输出打印项次(“面”);
}
您可以使用带有故障排除的开关盒
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;
}
}
你也可以写一个方法,告诉你一张卡片是否有一张脸!
这将更易于使用,并将防止冗余代码
您还可以使用类卡,而不是整数来保存卡值。
枚举也不坏
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;
}
}
案例2的主要内容:
public static void main(String args[]) {
int cardNumber = 10;
if(Card.hasFace(cardNumber)){
// your if case
}
else {
// your else case
}
}
开关盒结构更容易/更易于阅读如果(cardNumber==1 | | cardNumber>=11)将您的条件更改为
,
@AshtonAllen:好交易。如果这个(或这里的任何其他答案)回答了你的问题,那么你会接受这个答案。