gpt4 book ai didi

java - Java 中的数组洗牌

转载 作者:行者123 更新时间:2023-12-02 05:19:27 25 4
gpt4 key购买 nike

我正在摆弄一些示例代码,默认情况下,它会打印一个字符串数组,显示在我粘贴在下面的代码的顶部。我想随机化数组的显示方式。我尝试直接在声明数组的位置下方添加 Collections.shuffle(messages); ,但它不起作用。我使用了正确的导入,所以这不是问题。我不太清楚如何随机化数组,但这是我从我所做的研究中所能想到的最好的尝试。有人可以帮忙吗?

class Producer
implements Runnable
{
private BlockingQueue<String> drop;
List<String> messages = Arrays.asList(
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"Wouldn't you eat ivy too?");


public Producer(BlockingQueue<String> d) { this.drop = d; }

public void run()
{
try
{
for (String s : messages)
drop.put(s);
drop.put("DONE");
}
catch (InterruptedException intEx)
{
System.out.println("Interrupted! " +
"Last one out, turn out the lights!");
}
}
}

class Consumer
implements Runnable
{
private BlockingQueue<String> drop;
public Consumer(BlockingQueue<String> d) { this.drop = d; }

public void run()
{
try
{
String msg = null;
while (!((msg = drop.take()).equals("DONE")))
System.out.println(msg);
}
catch (InterruptedException intEx)
{
System.out.println("Interrupted! " +
"Last one out, turn out the lights!");
}
}
}

public class SynQApp
{
public static void main(String[] args)
{
BlockingQueue<String> drop = new SynchronousQueue<String>();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}

最佳答案

这应该有效:

public void run()
{
Collections.shuffle(messages);//randomize array before adding into the queue

try
{
for (String s : messages)
drop.put(s);
drop.put("DONE");
}
catch (InterruptedException intEx)
{
System.out.println("Interrupted! " +
"Last one out, turn out the lights!");
}
}

关于java - Java 中的数组洗牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26613969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com