Skip to content
Advertisement

Select Random element from ArrayList print then remove It

        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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement