从 ArrayList 中检索随机项 [英] Retrieving a random item from ArrayList

查看:32
本文介绍了从 ArrayList 中检索随机项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Java,但在使用 ArrayListRandom 时遇到了问题.

I'm learning Java and I'm having a problem with ArrayList and Random.

我有一个名为 catalogue 的对象,它有一个对象数组列表,这些对象是从另一个名为 item 的类创建的.

I have an object called catalogue which has an array list of objects created from another class called item.

我需要 catalogue 中的一个方法,该方法返回列表中一个 item 对象的所有信息.
item 需要随机选择.

I need a method in catalogue which returns all the information on one of the itemobjects in the list.
The item needs to be selected at random.

import java.util.ArrayList;
import java.util.Random;

public class Catalogue
{
    private Random randomGenerator = new Random();
    private ArrayList<Item> catalogue;

    public Catalogue ()
    {
        catalogue = new ArrayList<Item>();  
    }

    public Item anyItem()
    {
        int index = randomGenerator.nextInt(catalogue.size());
        System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
        return catalogue.get(index);
    }

当我尝试编译时,我收到一个错误,指向 System.out.println 行说..

When I try to compile I get an error pointing at the System.out.println line saying..

'找不到符号变量anyItem'

'cannot find symbol variable anyItem'

推荐答案

anyItem 是一个方法,System.out.println 调用在您的 return 语句之后,以便无论如何都不会编译,因为它无法访问.

anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.

可能想重写它:

import java.util.ArrayList;
import java.util.Random;

public class Catalogue
{
    private Random randomGenerator;
    private ArrayList<Item> catalogue;

    public Catalogue()
    { 
        catalogue = new ArrayList<Item>();
        randomGenerator = new Random();
    }

    public Item anyItem()
    {
        int index = randomGenerator.nextInt(catalogue.size());
        Item item = catalogue.get(index);
        System.out.println("Managers choice this week" + item + "our recommendation to you");
        return item;
    }
}

这篇关于从 ArrayList 中检索随机项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆