[英]How would I return one string at a time from a 2d array and not have any repeating ouputs until i have used the entire list?
I am trying to make a thing that selects one of five names from a 2d array of strings and return it.我正在尝试做一个从二维字符串数组中选择五个名称之一并将其返回的东西。 I only want to return one name at a time so I am using methods, but I also want the names to not repeat until all of them have been generated.我一次只想返回一个名字,所以我正在使用方法,但我也希望这些名字在生成所有名字之前不会重复。 I found something that was almost what I needed.我找到了几乎是我需要的东西。 However the output was still in a list and if I put it in a method it would just repeat.但是 output 仍在列表中,如果我将它放在一个方法中,它只会重复。
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
static void runArray() {
String[] peoples = {"Person 1", "Person 2", "Person 3", "Person 4"};
List<String> names = Arrays.asList(peoples);
Collections.shuffle(names);
for (String name : names) {
System.out.println(name + " ");
}
}
public static void main(String[] args) {
runArray();
}
}
One way of doing this is to randomly remove an item from the list each time you want to process a name, and continue to do so while there are more names left in the list.这样做的一种方法是每次要处理一个名称时从列表中随机删除一个项目,并在列表中还有更多名称时继续这样做。
eg例如
private static final Random R = new Random(System.currentTimeMillis());
private static String getRandomFromList(List<String> list) {
final int index = r.nextInt(list.size());
return list.remove(index);
}
private static void processName(String name) {
// do stuff here
}
public static void main(String[] args) {
final String[] peoples = {"Person 1", "Person 2", "Person 3", "Person 4"};
final List<String> names = Arrays.stream(peoples).collect(Collectors.toList());
while (!names.isEmpty()) {
final String name = getRandomFromList(names);
// Now do your processing for the name here e.g.
processName(name);
}
}
So you can call getRandomFromList
4 times (in the above example), getting a random name each time which you can then process.因此,您可以调用getRandomFromList
4 次(在上面的示例中),每次都获得一个随机名称,然后您可以对其进行处理。 Rather than assuming a specific number of entries I have just put this in a while loop with a check on whether there are any names left.我没有假设特定数量的条目,而是将其放入一个 while 循环中,检查是否还有剩余的名称。
If you need to call it more sequentially you can do something like below.如果您需要按顺序调用它,您可以执行如下操作。 It's good to make sure there are actually names left in the list and if not you can write out an error and return early, or throw an exception.最好确保列表中确实有名字,如果没有,你可以写出错误并提前返回,或者抛出异常。
if (names.isEmpty()) {
return; // or log error, or throw exception
}
String name = getRandomFromList(names);
// do stuff with first name
if (names.isEmpty()) {
return; // or log error, or throw exception
}
name = getRandomFromList(names);
// do stuff with second name
// etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.