Получение случайного элемента из ArrayList

Я изучаю Java, и у меня проблема с ArrayList и Random.

У меня есть объект с именем catalogue, в котором есть список объектов, созданных из другого класса item.

Мне нужен метод в catalogue, который возвращает всю информацию об одном из item объектов в списке.
item нужно выбирать случайным образом.

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, говорящую ...

'не удается найти символьную переменную anyItem'


person Will    schedule 17.02.2011    source источник
comment
Не только anyItem не имеет смысла в SOP, у вас есть возврат над этой строкой.   -  person asgs    schedule 17.02.2011
comment
Хех, вранье, это не выбор менеджеров, он выбирается наугад: S   -  person Mark Lalor    schedule 13.07.2012
comment
Лол, почему так много голосов за?   -  person Svetlin Zarev    schedule 18.02.2014


Ответы (12)


anyItem - это метод, а вызов System.out.println следует за вашим оператором return, поэтому он все равно не будет компилироваться, поскольку он недоступен.

Возможно, захочется переписать это так:

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;
    }
}
person Robby Pond    schedule 17.02.2011
comment
@Will randomGenerator имеет значение null. вам нужно создать его в своем конструкторе. Я обновлю пример кода. - person Robby Pond; 17.02.2011
comment
Для тех, кто пришел сюда в поисках более лаконичного ответа: Object randomItem = list.get (new Random (). NextInt (list.size ())) - person Marcelo Mason; 07.10.2012
comment
Если вы используете Java 7, list.get(ThreadLocalRandom.current().nextInt(list.size())) - person Jin Kwon; 16.08.2013
comment
общедоступные ‹T› T getRandom (список ArrayList ‹T›) {return list.get (random.nextInt (list.size ())); } - person larsaars; 09.04.2020

Ваш отпечаток приходит после того, как вы вернетесь - вы никогда не сможете добраться до этого утверждения. Кроме того, вы никогда не объявляли anyItem переменной. Вы можете захотеть

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

Часть toString - это просто быстрый ход - вы можете добавить метод getItemDescription, который возвращает полезную строку для этой цели ...

person hvgotcodes    schedule 17.02.2011
comment
Здравствуйте, этот параметр создает нулевой указатель в этой строке int index = randomGenerator.nextInt (catalogue.size ()); когда я пытаюсь вызвать метод. - person Will; 18.02.2011
comment
@will, вы никогда не инициализировали randomGenerator. Сделайте это в конструкторе каталога. - person hvgotcodes; 18.02.2011
comment
Ты прав, я забыл, Дох! - person Will; 18.02.2011

Вы должны удалить сообщение system.out.println из-под return, например:

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

оператор return в основном говорит, что функция теперь завершится. все, что включено за пределами оператора return, которое также входит в его область действия, приведет к поведению, которое вы испытали

person james    schedule 17.02.2011
comment
Единственная разница между наличием it.toString() и просто it состоит в том, что первое может генерировать исключение NullPointerException, а второе - нет. Если it находится в переменной, почему бы не вернуть его? - person Peter Lawrey; 17.02.2011
comment
хорошая точка зрения. Я сделаю изменение в ответе - person james; 17.02.2011
comment
Привет, это не работает. Он дает нулевой указатель на строку int index = randomGenerator.nextInt (catalogue.size ()); - person Will; 18.02.2011

Вот и все, используя Generics:

private <T> T getRandomItem(List<T> list)
{
    Random random = new Random();
    int listSize = list.size();
    int randomIndex = random.nextInt(listSize);
    return list.get(randomIndex);
}
person BullyWiiPlaza    schedule 21.12.2016

попробуй это

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

И я настоятельно рекомендую вам приобрести книгу, например, Ivor Horton's Beginning Java 2.

person Augusto    schedule 17.02.2011

anyItem никогда не объявлялся как переменная, поэтому логично, что он вызывает ошибку. Но что еще более важно, у вас есть код после оператора возврата, и это вызовет ошибку недоступного кода.

person Hovercraft Full Of Eels    schedule 17.02.2011
comment
Привет. Как объявить переменную anyItem? - person Will; 18.02.2011
comment
Вы не хотите, не внутри этого метода. Есть лучшие предложения о том, что делать выше. - person Hovercraft Full Of Eels; 18.02.2011
comment
Здравствуйте! Все приведенные выше предложения дают нулевой указатель на строку int index = randomGenerator.nextInt (catalogue.size ()); - person Will; 18.02.2011
comment
Они давали нулевой указатель, потому что я забыл добавить randomGenerator = new Random (); в конструкторе. Дох! - person Will; 18.02.2011
comment
Тогда либо randomGenerator, либо catalog имеют значение NULL. Проверьте их, чтобы убедиться, что они равны нулю чуть выше этой строки, с помощью пары операторов println. Вы вызываете этот код перед инициализацией любого из этих двух объектов? Изменить: неважно - я только что видел ваш ответ. - person Hovercraft Full Of Eels; 18.02.2011

System.out.println («Выбор менеджеров на этой неделе» + anyItem + «наша рекомендация вам»);

Вы не инициализировали или даже не объявили переменную anyItem.

Этот код: + anyItem +

означает получение значения метода toString объекта anyItem

Второе, почему это не сработает. У вас есть System.out.print после оператора возврата. Программа никогда не могла дойти до этой черты.

Вероятно, вам нужно что-то вроде:

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

}

btw: в Java это правило помещает фигурные скобки в ту же строку, что и объявление функции.

person malejpavouk    schedule 17.02.2011
comment
Привет. Я переместил system.out.println в перед возвратом. Но я все еще получаю ошибку NullPointer, когда пытаюсь вызвать метод. Он указывает на эту строку int index = randomGenerator.nextInt (catalogue.size ()); - person Will; 18.02.2011
comment
Сначала вы должны инициализировать случайный. Лучшее решение для вас - в конструкторе. Без инициализации переменная содержит null, что означает, что здесь должна быть переменная типа Random. Без него вы запрашиваете пустую область памяти, чтобы дать вам nextInt. Следовательно, исключение nullpointerException - person malejpavouk; 18.02.2011

Как я вижу, код
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
недоступен.

person user2763281    schedule 23.07.2015
comment
То, как он писал свой код, также вызвало бы ошибку StackOverFlow (с AnyItem == ›AnyItem ()) - person MrKickkiller; 17.12.2015

См. https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57.

public static void main(String[] args) {
    RandomList<String> set = new RandomList<>();

    set.add("a", 10);
    set.add("b", 10);
    set.add("c", 30);
    set.add("d", 300);

    set.forEach((t) -> {
        System.out.println(t.getChance());
    });

    HashMap<String, Integer> count = new HashMap<>();
    IntStream.range(0, 100).forEach((value) -> {
        String str = set.raffle();
        count.put(str, count.getOrDefault(str, 0) + 1);
    });

    count.entrySet().stream().forEach(entry -> {
        System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
    });
}

Выход:

2.857142857142857

2.857142857142857

8.571428571428571

85.71428571428571

a: 2

b: 1

c: 9

d: 88

person NathanSoares    schedule 14.04.2017

Решение нехорошее, даже если вы исправили свое имя и недостижимость этой распечатки.

на вещи, на которые вы также должны обратить внимание: 1. начальное число случайности и большие данные, число элементов настолько велико, что возвращено число из этого случайного ‹itemlist.size ().

  1. вы не обрабатываете многопоточность, вы можете получить индекс за пределами связанного исключения
person Neo Li    schedule 08.04.2013
comment
Кто сказал, что он должен быть потокобезопасным? Лучше предположить, что это не так. Возможно, вы даже находитесь в среде, где в основном запрещено обрабатывать параллелизм самостоятельно (EJB, ...). - person ymajoros; 11.10.2013

Вот лучший способ сделать что-то:

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

public class facultyquotes
{
    private ArrayList<String> quotes;
    private String quote1;
    private String quote2;
    private String quote3;
    private String quote4;
    private String quote5;
    private String quote6;
    private String quote7;
    private String quote8;
    private String quote9;
    private String quote10;
    private String quote11;
    private String quote12;
    private String quote13;
    private String quote14;
    private String quote15;
    private String quote16;
    private String quote17;
    private String quote18;
    private String quote19;
    private String quote20;
    private String quote21;
    private String quote22;
    private String quote23;
    private String quote24;
    private String quote25;
    private String quote26;
    private String quote27;
    private String quote28;
    private String quote29;
    private String quote30;
    private int n;
    Random random;

    String teacher;


    facultyquotes()
    {
        quotes=new ArrayList<>();
        random=new Random();
        n=random.nextInt(3) + 0;
        quote1="life is hard";
        quote2="trouble shall come to an end";
        quote3="never give lose and never get lose";
        quote4="gamble with the devil and win";
        quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
        quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
        quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
        quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
        quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
        quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
        quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
        quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
        quote13="No one can make you feel inferior without your consent.";
        quote14="Let him who would enjoy a good future waste none of his present.";
        quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
        quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
        quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
        quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
        quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
        quote20="It is our choices, that show what we truly are, far more than our abilities.";
        quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
        quote22="The successful warrior is the average man, with laser-like focus.";
        quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
        quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
        quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
        quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
        quote27="Don’t let the fear of losing be greater than the excitement of winning.";
        quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
        quote29="There is nothing permanent except change.";
        quote30="You cannot shake hands with a clenched fist.";

        quotes.add(quote1);
        quotes.add(quote2);
        quotes.add(quote3);
        quotes.add(quote4);
        quotes.add(quote5);
        quotes.add(quote6);
        quotes.add(quote7);
        quotes.add(quote8);
        quotes.add(quote9);
        quotes.add(quote10);
        quotes.add(quote11);
        quotes.add(quote12);
        quotes.add(quote13);
        quotes.add(quote14);
        quotes.add(quote15);
        quotes.add(quote16);
        quotes.add(quote17);
        quotes.add(quote18);
        quotes.add(quote19);
        quotes.add(quote20);
        quotes.add(quote21);
        quotes.add(quote22);
        quotes.add(quote23);
        quotes.add(quote24);
        quotes.add(quote25);
        quotes.add(quote26);
        quotes.add(quote27);
        quotes.add(quote28);
        quotes.add(quote29);
        quotes.add(quote30);
    }

    public void setTeacherandQuote(String teacher)
    {
        this.teacher=teacher;
    }

    public void printRandomQuotes()
    {
        System.out.println(quotes.get(n++)+"  ~ "+ teacher);  
    }

    public void printAllQuotes()
    {
        for (String i : quotes)
        {
            System.out.println(i.toString());
        }
    }
}
person Abdul Rehman    schedule 31.10.2017
comment
Пожалуйста, не используйте нумерованные переменные. Кроме того, нам действительно не нужно видеть больше трех, чтобы понять суть - person OneCricketeer; 10.02.2018

person    schedule
comment
Что именно здесь ловят? Вы должны проверить, является ли список пустым или нулевым, а не использовать try catch - person OneCricketeer; 10.02.2018