简体   繁体   中英

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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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