我是 Java 的菜鸟,需要一些帮助。我想知道如何在不复制整个语句的情况下为每个nameOne,nameTwo和NameThree字符串获取随机名称switch。有人可以就如何在不膨胀我的代码的情况下执行此操作给我建议吗?我的实际名单很长。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 回答
慕仙森
TA贡献1827条经验 获得超7个赞
一种简单的方法是将它们分成两个Array(一个用于女性名字,一个用于男性名字),然后有类似的东西
if(gender1 == 'w'){
nameOne = femaleNames[randomNum];
}
femaleNames你Array的女性名字在哪里,randomNum是你的随机数。只要确保randomNum在你的范围内Array
添加回答
举报
0/150
提交
取消