是否有可能声明4个选项,而Java必须随机选择1个?

是否有可能声明4个选项,而Java必须随机选择1个?,java,Java,我在做坦克游戏。我希望我的敌人从面板的一侧随机发射,如下所示: scherm表示屏幕/面板 breedte表示宽度 hoogte表示高度 public void launch() { //from upside x_pos = rand.nextInt(Tanks.getSchermBreedte()); y_pos = 0; //leftside x_pos = 0; y_pos = rand.nextInt(Tanks.getScherm

我在做坦克游戏。我希望我的敌人从面板的一侧随机发射,如下所示:

scherm
表示屏幕/面板
breedte
表示宽度
hoogte
表示高度

public void launch() 
{
    //from upside
    x_pos = rand.nextInt(Tanks.getSchermBreedte());
    y_pos =  0;

    //leftside
    x_pos = 0;
    y_pos = rand.nextInt(Tanks.getSchermHoogte());

    //lower side
    x_pos = rand.nextInt(Tanks.getSchermBreedte());
    y_pos = Tanks.getSchermHoogte();

    //right
    x_pos = Tanks.getSchermBreedte();
    y_pos = rand.nextInt(Tanks.getSchermHoogte());

}

我希望Java选择其中一个选项,但我真的不知道如何做到这一点

使用
java.util.Random.nextInt(4)
,它提供从0到3的随机数。然后使用switch语句选择一个选项

public void launch() {
      int random = java.util.Random.nextInt(3);

      switch (random) {
        case 0:
            //from upside
            x_pos = rand.nextInt(Tanks.getSchermBreedte());
            y_pos =  0;
        break;
        case 1: 
          //leftside
          x_pos = 0;
          y_pos = rand.nextInt(Tanks.getSchermHoogte());
        break;
        case 2:
            //lower side
            x_pos = rand.nextInt(Tanks.getSchermBreedte());
            y_pos = Tanks.getSchermHoogte();
        break;
        case 3:
            //right
            x_pos = Tanks.getSchermBreedte();
            y_pos = rand.nextInt(Tanks.getSchermHoogte());
        break;
      }
}

您可以将所有点放在一个数组中,并使用以下命令随机选择坐标:

    public static int getRandom(int[] array) {
        int rnd = new Random().nextInt(array.length);
        return array[rnd];
    }

如果分别为x和y坐标维护阵列,则可以将其用于x和y坐标。即使您维护了一个,代码也可以稍加修改,仍然很有用

是的,您可以通过内置函数生成随机数,并且您可以在switch case语句中以case形式提供生成的数字存储(x,y)在
点协调
?非常感谢,但我的敌人只在左上角发射,我不知道为什么