在开关盒中选择随机盒

问题描述 投票:0回答:5

我有一个有15个以上案例的开关案例。 switch case触发一个整数变量,每次执行时递增1,并在所有case执行并重新启动后返回值1。我将如何做到这一点,以便我的开关案例触发随机案例,我不想再从头开始..只是在每个提示上随机执行案例。

码:

if(guns)
            {
                if(mygun <9){
                    mygun += 1;
                }else 
                {
                    mygun = 1;
                }
                switch(mygun){
                    case 1:
                        thegun = "︻デ═一";
                        break;
                    case 2:
                        thegun = "*-* ︻┳デ═—";
                        break;
                    case 3:
                        thegun = "▄︻̷̿┻̿═━一";
                        break;
                    case 4:
                        thegun = "(⌐■_■)--︻╦╤─ - - -";
                        break;
                    case 5: 
                        thegun = "︻╦̵̵͇══╤─";
                        break;
                    case 6:
                        thegun = "✯╾━╤デ╦︻✯";
                        break;
                    case 7:
                        thegun = " ̿̿ ( ▀ ͜͞ʖ▀)=€̿̿▄︻̷̿┻̿═━一";
                        break;
                    case 8:
                        thegun = "(⌐■_■)–︻╦╤─";
                        break;
                    case 9:
                        thegun = "╾━╤デ╦︻༼ಠ益ಠ༽︻╦̵̵͇══╤─";
                        break;
                }

}

java
5个回答
1
投票

假设您要生成1到15之间的随机数。

你可以尝试这两种方法:

方法1:使用java.util.Random

Random rand = new Random();
switch(rand.nextInt(15)+1)// default range is from(0 to 14) +1 at the end makes the range from(1 to 15)
{
 // your cases here
}

这样可以避免重置mygun变量的值。

参考:java.util.Random class

方法2:

使用java.lang.Math.random()

参考:java.lang.Math


2
投票

只需为您的交换机案例创建一个包装器方法。此方法将int作为输入并将该输入传递给开关。然后将任意随机值传递给此方法并观察它的执行情况。


1
投票

使用Math.random()生成随机数。但是Math.random()会生成一个从0到1的随机数。因此,要生成一个范围内的随机数,例如从1到16,您可以使用:Math.floor((Math.random() * 16) + 1);并将此输出作为开关案例的输入。


0
投票

简单的方法是,生成一个随机数并使用它来识别要执行的案例。有多种方法可以在Java中生成可用于完成工作的随机数。有关更多信息,请参阅this question

Random r = new Random();
int Result = r.nextInt(20);
switch(result){
  case 1:
   ...
}

0
投票

只需使用Random类

Random random=new Random();

int random no=++random.nextInt(15);

这将生成随机数。在开关盒中使用它。

要么

使用randomNo = ++(Math.random * 15)

比案件数量少15比1。

© www.soinside.com 2019 - 2024. All rights reserved.