如何在开关内随机定义多个变量?

时间:2018-10-11 17:29:43

标签: java switch-statement

我是Java的菜鸟,在这方面需要一些帮助。我不知道如何在不复制整个nameOne语句的情况下为每个nameTwoNameThreeswitch字符串获取一个随机名称。有人可以给我建议如何做到这一点而不会使我的代码膨胀吗?我的实际姓名很长。

public class multipleNamesPicker {public static void main(String[] args) {

    String nameOne = null;
    String nameTwo = null;
    String nameThree = null;
    char gender1 = 'a'; 
    char gender2 = 'a';
    char gender3 = 'a';

    byte randomNumber1 = (byte)(Math.random()*2+1);
    switch(randomNumber1) {
      case 1: gender1 = 'w';
      case 2: gender1 = 'm';
    }

    byte randomNumber2 = (byte)(Math.random()*5+1);
    if(gender1 == 'w'){
        switch(randomNumber2) {
           case 1: nameOne = "Edna";
           case 2: nameOne = "Martha";
           case 3: nameOne = "Berta";
           case 4: nameOne = "Margaret";
           case 5: nameOne = "Anna";
        }
     }

     else{
        switch(randomNumber2) {
          case 1: nameOne = "Peter";
          case 2: nameOne = "Paul";
          case 3: nameOne = "Pablo";
          case 4: nameOne = "Henry";
          case 5: nameOne = "George";
        }
     }

    System.out.println(nameOne + ", " + nameTwo + " and " + nameThree);}
}

1 个答案:

答案 0 :(得分:1)

一种简单的方法是将它们放在两个Array中(一个用于女性名称,一个用于男性名称),然后添加类似的内容

if(gender1 == 'w'){
    nameOne = femaleNames[randomNum];
}

其中femaleNames是您的Array女名,randomNum是您的随机数。只要确保randomNum在您的Array的范围内