如何在Java for Android中编写随机引用生成器?

时间:2012-02-23 12:44:05

标签: android string random

我对Java for Android很新,基本上只是一个尝试为HTC手机制作一些基本应用程序的菜鸟。到目前为止,主要通过复制代码,我编写的应用程序将编写“Hello,World”,打印随机数并显示图片,这些在我的手机上运行良好。

我现在想要结合我已经完成的工作并编写一个应用程序,它将从指定列表中生成随机引用并将其打印在屏幕上。刷新按钮也不错。

我首先看了这些链接作为起点: Forrst Stack Overflow

然而,我认为我现在正试图将这两者结合起来。我开始创建一个引号数组,生成一个随机数并将其分配给引号,然后尝试获取tv.setText方法来编写它。

感激不尽的任何帮助!谢谢!

这是我到目前为止所做的:

package com.Me;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Random;

public class QuoteActivity extends Activity {

int numQuotes = 10;
String[] quotes = new String[numQuotes] {"John", "Mary", "Bob"};
String randomQuote = quotes[Math.floor(Math.random() * numQuotes)];

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Make a new text view passing Activity object
    TextView tv = new TextView(this);
    //Set a text into view

    tv.setText(randomQuote);
    //set the view into activity view container
    setContentView(tv);
}

}

2 个答案:

答案 0 :(得分:3)

好的,首先是一些基本的东西:你没有为引号分配数字,你使用随机数来索引引号数组。话虽如此,这样的事情可以解决问题:

String[] quotes = new String[] {"q1", "q2", "q3"};
String randomQuote = quotes[(int) (Math.random() * quotes.length)];

请注意,您不能同时设置数组的大小并进行初始化。即或者你喜欢上面的,或者你做了类似的事情:

int numQuotes = 3;
String[] quotes = new String[numQuotes];
quotes[0] = "q1";
quotes[1] = "q2";
quotes[2] = "q3";

答案 1 :(得分:1)

我在您的代码中看到了一些错误:

  • 您可以通过

  • 初始化数组

String[] quotes = new String[]{"1", "2", "3"};

String[] quotes = new String[3];
quotes[0] = "1";
quotes[1] = "2";
quotes[2] = "3";
  • Math.floor()和Math.random()返回double,您应该使用int访问数组元素。你应该转换为int。你实际上并不需要floor()因为random()返回正值。
  • 如果您尝试访问不存在的数组元素,您将收到异常。如果你有3个元素的数组,math.random()* 10给你4 - 你会崩溃。

我建议:

int randomElemenetIndex = (int) (Math.random() * 10) % 3; //This way you will have 0, 1 or 2
...
tv.setText(quotes[randomElementIndex]);