如何编写从数组中随机选择引用的函数? - Android Java

时间:2015-02-13 00:40:42

标签: java android arrays random

我正在关注android编码教程,并尝试随机选择引用。以下是未经修改的代码。

       final ArrayList<Quote> quoteList = new ArrayList<Quote>();

    Quote quote1 = new Quote("Would I rather be feared or loved? Easy. Both. I want people to fear how much they love me.", "Michael Scott");
    quoteList.add(quote1);

    Quote quote2 = new Quote("I'm not superstitious. But I am a little stitious.", "Michael Scott");
    quoteList.add(quote2);

    Quote quote3 = new Quote("I like waking up to the smell of bacon.", "Michael Scott");
    quoteList.add(quote3);

    Quote quote4 = new Quote("Wikipedia is the best thing ever. Anyone in the world can write anything they want about any subject. So you know you are getting the best possible information.", "Michael Scott");
    quoteList.add(quote4);

    Quote quote5 = new Quote("Mo' money, mo' problems.", "Michael Scott");
    quoteList.add(quote5);

    Quote quote6 = new Quote("SWAG! Stuff We All Get.", "Michael Scott");
    quoteList.add(quote6);

    Quote quote7 = new Quote("You just gots to get your freak on.", "Michael Scott");
    quoteList.add(quote7);

    Quote quote8 = new Quote("We're all homos. Homo sapiens.", "Michael Scott");
    quoteList.add(quote8);

    Quote quote9 = new Quote("Hate to see you leave but love to watch you go. 'Cause of your butt.", "Michael Scott");
    quoteList.add(quote9);

    Quote quote10 = new Quote("If a baby were president, there would be no taxes, there would be no war.", "Michael Scott");
    quoteList.add(quote10);
    //Add more quotes here


    touch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (count < quoteList.size()) {
                Quote q = quoteList.get(count);
                quoteText.setText(q.getQuote());
                personText.setText(q.getPerson());
                count = count + 1;
            } else{
                count = 0;
            }
        }
    });
}

如果有人可以解释如何让屏幕被触摸时随机选择一个引用,而不是逐个浏览它们,我会非常感激。

4 个答案:

答案 0 :(得分:1)

您必须生成0之间的随机数,无论您的列表是多长

Random rand = new Random()
int  n = rand.nextInt(quoteList.size() - 1);

然后使用获取该索引的报价

Quote random = quoteList.get(n);

答案 1 :(得分:0)

Random random = new Random();    
int randomNum = random.nextInt(quoteList.size() - 1);
Quote randomQuote = quoteList.get(randomNum);

答案 2 :(得分:-1)

随机选择一个引用:

int randomNum = (int)(Math.random()*(quoteList.size() - 1));
Quote randomQuote = quoteList.get(randomNum);

答案 3 :(得分:-1)

String yourString = quoteList[new Random().nextInt(quoteList.length)];