为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

红颜莎娜 2022-01-12 17:06:54
所以我有一个班级杯,它是班级比赛的一部分。公共 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()) 所在的行上有一个空指针异常。只是非常令人困惑,因为我觉得这应该是正确的。谢谢!!!
查看完整描述

1 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

在您的构造函数中,您不需要,Random r因为您已经有了private Random r;


其余的似乎正在工作。注意您的remove(int m)方法,以免用户传递大于 ArrayList 大小的值,以避免出现 IndexOutOfBoundsException。


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);


        //here you should use your r attribute

        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);

    }

}


查看完整回答
反对 回复 2022-01-12
  • 1 回答
  • 0 关注
  • 172 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号