我有一个开关盒,里面有 15 个以上的盒子。 switch case 触发一个整数变量,该变量在每次执行时加 1,并在所有 case 执行并重新开始后变回值 1。 我该怎么做才能使我的 switch case 触发随机 case,并且我不想从头开始它......只需在每个提示上随机执行 case 即可。
代码:
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;
}
}
最佳答案
假设您要生成 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
变量的值。
方法2:
使用java.lang.Math.random()
关于java - 在 switch case 中选择随机 case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081879/