Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading