繁体   English   中英

我如何一次从二维数组返回一个字符串并且在我使用整个列表之前没有任何重复输出?

[英]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?

我正在尝试做一个从二维字符串数组中选择五个名称之一并将其返回的东西。 我一次只想返回一个名字,所以我正在使用方法,但我也希望这些名字在生成所有名字之前不会重复。 我找到了几乎是我需要的东西。 但是 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();
  }
}

这样做的一种方法是每次要处理一个名称时从列表中随机删除一个项目,并在列表中还有更多名称时继续这样做。

例如

    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);
        }
    }

因此,您可以调用getRandomFromList 4 次(在上面的示例中),每次都获得一个随机名称,然后您可以对其进行处理。 我没有假设特定数量的条目,而是将其放入一个 while 循环中,检查是否还有剩余的名称。

如果您需要按顺序调用它,您可以执行如下操作。 最好确保列表中确实有名字,如果没有,你可以写出错误并提前返回,或者抛出异常。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM