如何获得不重复的随机整数?

我有这个Android应用程序,它非常简单,基本上我从数据库中获取一个字符串,然后按下一个按钮并获取另一个字符串,除了我想获取随机字符串并且一旦它们被“使用”后就不再重复它们


    public String getQuestion() {


        mydManager.openReadable();

        ArrayList<String> tableContent = mydManager.retrieveRows();


        int size = tableContent.size();


        Random rand = new Random();

        int rand_int = rand.nextInt(size);

        String a = tableContent.get(rand_int);


        String[] myarray = a.split("\n");

        String Rquestion = (myarray[1]);

        question = findViewById(R.id.question);

        question.setText(Rquestion);


        return a;

    }

一旦我得到数组中索引为 1 的问题,我不想在调用此函数时再次得到同样的问题


繁花如伊
浏览 71回答 3
3回答

FFIVE

ArrayList<String>您可以将 声明并初始化为全局变量,然后在获取随机变量后将其从数组中删除,而不是每次生成新问题时都检索行private ArrayList<String> tableContent;Random rand = newpublic YourClass yourConstructor () { // or MainActivity initializer if android studio&nbsp; &nbsp; &nbsp; &nbsp; mydManager.openReadable();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; tableContent = mydManager.retrieveRows();}public String getQuestion() {&nbsp; &nbsp; &nbsp; &nbsp; int size = tableContent.size();&nbsp; &nbsp; &nbsp; &nbsp; int rand_int = rand.nextInt(size);&nbsp; &nbsp; &nbsp; &nbsp; String a = tableContent.get(rand_int);&nbsp; &nbsp; &nbsp; &nbsp; //remove the element from arraylist&nbsp; &nbsp; &nbsp; &nbsp; tableContent.remove(a);&nbsp; &nbsp; &nbsp; &nbsp; String[] myarray = a.split("\n");&nbsp; &nbsp; &nbsp; &nbsp; String Rquestion = (myarray[1]);&nbsp; &nbsp; &nbsp; &nbsp; question = findViewById(R.id.question);&nbsp; &nbsp; &nbsp; &nbsp; question.setText(Rquestion);&nbsp; &nbsp; &nbsp; &nbsp; return a;}这应该可以解决问题

暮色呼如

好的,随着更多问题被添加到您的数据库中,您无法仅从数据库中检索问题列表一次。您必须在每次单击按钮时执行此操作。所以现在你有两个选择:维护已使用的索引/数字的列表:当您生成下一个随机数时,它应该与这些索引/数字不同。如果相同则重新生成。此外,为此,添加到数据库或从数据库检索的问题不应更改先前问题的顺序。从数组列表中删除使用过的问题(如果不在其他地方使用则不需要)和数据库

慕无忌1623718

全局数组列表声明&nbsp;ArrayList<Integer> integers; // as globle//创建时integers = new ArrayList<>();public int gen(int i) {&nbsp; &nbsp; &nbsp; &nbsp; int alldata = i;&nbsp; &nbsp; &nbsp; &nbsp; Random rand = new Random();&nbsp; &nbsp; &nbsp; &nbsp; int rand_int = rand.nextInt(i);&nbsp; &nbsp; &nbsp; &nbsp; if (integers.size() == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; integers.add(rand_int);&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (integers.contains(rand_int)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return gen(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; integers.add(rand_int);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return rand_int;&nbsp; &nbsp; }int size = tableContent.size();String a = tableContent.get(gen(size));上面的代码每次都会生成新的整数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java