猿问

如何在我的 ArrayList 中生成随机索引?

所以我有一个班级杯,它是班级比赛的一部分。公共 int select() 方法必须返回 c 中的移动。我需要在c中生成一个随机索引,我被告知通过生成一个从零到不包括ArrayList大小的随机数来做到这一点。这是我所拥有的:


import java.util.ArrayList;

import java.util.Random;

public class Cup {


    ArrayList<Integer> c = new ArrayList<Integer>();

    private Random r;


    public Cup() {

        c.add(1);

        c.add(2);

        c.add(3);

        Random r = new Random();

    }


    public int count() {

        return c.size();

    }


    public int select() {

        int index = r.nextInt(c.size());

        return c.get(index);

    }


    public void remove(int m) {

        c.remove(m);

    }

}

当我在我正在使用的游戏中编译它时,它编译正确,但告诉我在 r.nextInt(c.size()) 所在的行上有一个空指针异常。只是非常令人困惑,因为我觉得这应该是正确的。谢谢!!!


红颜莎娜
浏览 173回答 1
1回答

尚方宝剑之说

在您的构造函数中,您不需要,Random r因为您已经有了private Random r;其余的似乎正在工作。注意您的remove(int m)方法,以免用户传递大于 ArrayList 大小的值,以避免出现 IndexOutOfBoundsException。import java.util.ArrayList;import java.util.Random;public class Cup {&nbsp; &nbsp; ArrayList<Integer> c = new ArrayList<Integer>();&nbsp; &nbsp; private Random r;&nbsp; &nbsp; public Cup() {&nbsp; &nbsp; &nbsp; &nbsp; c.add(1);&nbsp; &nbsp; &nbsp; &nbsp; c.add(2);&nbsp; &nbsp; &nbsp; &nbsp; c.add(3);&nbsp; &nbsp; &nbsp; &nbsp; //here you should use your r attribute&nbsp; &nbsp; &nbsp; &nbsp; r = new Random();&nbsp; &nbsp; }&nbsp; &nbsp; public int count() {&nbsp; &nbsp; &nbsp; &nbsp; return c.size();&nbsp; &nbsp; }&nbsp; &nbsp; public int select() {&nbsp; &nbsp; &nbsp; &nbsp; int index = r.nextInt(c.size());&nbsp; &nbsp; &nbsp; &nbsp; return c.get(index);&nbsp; &nbsp; }&nbsp; &nbsp; public void remove(int m) {&nbsp; &nbsp; &nbsp; &nbsp; c.remove(m);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答