【发布时间】:2017-11-15 01:34:59
【问题描述】:
目前正在制作一个程序,该程序将从两个不同的数组生成字符串列表,但现在它所做的只是重复生成字符串所需的次数,有时会重复生成多个字符串。
public class ListGenerator
{
public static void main(String[] args)
{
//number generator to determine which string to print
Random generator = new Random();
int rand;
//counter to determine number of printed lines
int counter = 0;
//coin flip to say which array the string will come from
Random coinFlip = new Random();
int coin;
String[] list1;
list1 = new String[5]
list1[0] = "Alpha"
list1[1] = "Beta"
list1[2] = "Charlie"
list1[3] = "Delta"
list1[4] = "Echo"
String[] list2;
list2 = new String[5]
list2[0] = "Apple"
list2[1] = "Pear"
list2[2] = "Grape"
list2[3] = "Banana"
list2[4] = "Orange"
for(counter = 0; counter < 15; counter++)
{
coin = coinFlip.nextInt(2)+1;
if(coin == 1)
{
rand = generator.nextInt(list1.length);
System.out.println(list1[rand]);
}
else if(coin == 2)
{
rand = generator.nextInt(list2.length);
System.out.println(list2[rand]);
}
}
}
}
有没有办法让我在生成的 15 行中生成像“Apple”或“Beta”这样的字符串不超过两次?
预期输出:
(1) Apple [printed first time]
(2) Charlie [printed first time]
(3) Pear [printed first time]
(4) Beta [printed first time]
(5) Apple [printed second time]
(6) Echo [printed first time]
(7) Banana [printed first time]
(8) Banana [printed second time]
(9) Echo [printed second time]
(10) Alpha [printed first time]
(11) Grape [printed first time]
(12) Delta [printed first time]
(13) Beta [printed second time]
(14) Orange [printed first time]
(15) Grape [printed second time]
其中 5 个字符串生成了两次但不超过两次,但在我的代码中,它可以生成任何字符串 3、4、5 等次。
我知道我的代码组织得不是最好或最有效的,我只需要关于这个重复问题的帮助
【问题讨论】:
-
顺便说一句,您在初始化过程中重复
list2[0]五次。
标签: java arrays math random duplicates