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

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

问题描述

我学习Java和我在与的ArrayList RandomGenerator

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

目录称为对象已经从所谓的项目另一个类创建的对象的数组列表。
我需要目录返回列表中的对象项目之一,所有的信息的方法。
需要在随机选择的项目
我用随机数发生器util的,但我无法得到它的工作。我不知道是什么我做错了。

I have an object called catalogue which has an array list of objects created from another class called 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. I have used the random generator util but I cannot get it working. I can't work out what I have done wrong.

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

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

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

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

当我尝试编译我得到的的System.out.println 行指着说无法找到符号变量anyItem错误

When I try to compile I get an error pointing at the System.out.println line saying 'cannot find symbol variable anyItem'

任何帮助非常AP preciated :)
谢谢

Any help greatly appreciated :) Thanks

推荐答案

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天全站免登陆