source

ArrayList에서 임의 항목 검색

goodcode 2022. 9. 3. 13:17
반응형

ArrayList에서 임의 항목 검색

자바를 배우고 있는데 자바를 배우는데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을 찾을 수 없습니다.'

anyItem메서드 및System.out.printlncall은 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;
    }
}
public static Item getRandomChestItem(List<Item> items) {
    return items.get(new Random().nextInt(items.size()));
}

당신의 지문은 당신이 돌아온 후에 옵니다. 당신은 그 진술에 도달할 수 없습니다.또한 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 부분은 간단한 설명입니다.이 용도로 유용한 String을 반환하는 메서드 'getItemDescription'을 추가할 수 있습니다.

여기에서는 다음을 사용합니다.

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

를 삭제해야 합니다.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그 범위 내에 있는 진술은 당신이 경험한 행동을 야기할 것이다.

이거 먹어봐

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

이보르 호튼의 '시작 자바 2' 같은 책을 사시길 강력히 권합니다

anyItem은 변수로 선언된 적이 없기 때문에 오류가 발생하는 것은 당연합니다.그러나 더 중요한 것은 return 스테이트먼트 뒤에 코드가 있기 때문에 도달할 수 없는 코드 오류가 발생합니다.

System.out.println("이번 주에 관리자가 선택한 것") + any항목 + "당사가 권장하는 사항";

변수 anyItem이 초기화되거나 선언되지 않았습니다.

이 코드: + any항목 +

오브젝트 anyItem의 toString 메서드 값을 취득하는 것을 의미합니다.

두 번째 이유는 이것이 작동하지 않는 것입니다.반환문 뒤에 System.out.print 가 표시됩니다.프로그램이 THA 라인에 도달하지 못했습니다.

다음과 같은 것이 필요할 수 있습니다.

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에서는 함수의 선언과 같은 줄에 컬리 괄호를 배치하는 대류입니다.

를 알 수 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
도달할 수 없습니다.

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

인쇄물의 이름이나 도달 불능 스테이트먼트를 수정해도 해결 방법이 좋지 않습니다.

주의해야 할 사항도 1. 랜덤성 시드 및 대용량 데이터는 해당 랜덤 <아이템 리스트.사이즈>의 반환된 num이 너무 큽니다.

  1. 다중 스레드를 처리하지 않았습니다. 인덱스가 범위를 벗어났을 수 있습니다.

여기 더 나은 방법이 있습니다.

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

언급URL : https://stackoverflow.com/questions/5034370/retrieving-a-random-item-from-arraylist

반응형