Home > Net >  Select Random element from ArrayList print then remove It
Select Random element from ArrayList print then remove It

Time:04-26

        ArrayList<String> question = new ArrayList<String>();

        Scanner scan = new Scanner(System.in);
            for (int i=0;i<userQuestionList.size();i  ){ //get questions
                if (i%2 == 0){
                    question.add(userQuestionList.get(i));
                }
            }

            for (int j = 0; j < question.size(); j  ) { // get ans
                Random ran = new Random();
                System.out.print(question.remove((ran.nextInt(question.size() 1))) " ");
                String ans = scan.nextLine();
                answer.add(ans);
            }
    }

Hi so I have this array list of questions and I want to choose it randomly then delete it one by one until there's no more so that It wont load the same question twice but there is some problem for example I have 3 questions in the question arraylist sometime it only loads 1 or two even the same question then throw me out of bound can anyone help?

CodePudding user response:

Fast and simple, make use of Collections.shuffle

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");

        while (!list.isEmpty()) {
            // You don't need to do this on each iteration
            // but this is going to give you a really
            // random result
            Collections.shuffle(list);
            String value = list.remove(0);
            System.out.println(value);
        }
    }
}

First run...

e
a
c
d
b

Second run...

a
e
d
b
c

Obviously, each run will give different results

CodePudding user response:

Here's a terrible example:

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");

Random rand = new Random();

System.out.println("Original list: "   list);

int r = rand.nextInt(list.size());

System.out.println(list.get(r));

list.remove(r);

System.out.println("New list: "   list);

Console:
Original list: [a, b, c, d, e]
e
New list: [a, b, c, d]
  • Related