生成一个整数并将其用作字符串数组的索引

Hob*_*obo 0 java android

我最近开始使用android编程,只掌握java的基础知识.我的代码遇到了问题,我的目标是在单击按钮后显示已经在我的数组中编程的随机选择的文本(onclick事件).

public void magicbegins() //
{
    int min = 0;
    int max = 3;
    Random r = new Random();
    int rand = r.nextInt(max - min + 1) + min;
    //generating random number from 0 to 3 to use as index in later event
    String[] magictext = {"yes", "no", "maybe"};

    TextView text = (TextView) findViewById(R.id.textView1);
    //using the generated number as index for programmed string array
    text.setText(magictext[rand]);
}
Run Code Online (Sandbox Code Playgroud)

如果任何情况下不建议使用此代码,那么是否有人会提供一个示例脚本,该脚本与我的目标至少相似?

Ted*_*opp 5

由于您的索引需要为0,1或2,因此只需使用r.nextInt(3)(或者,如果您对变量声明重新排序r.nextInt(magictext.length)).你肯定不应该使用,r.nextInt(max - min + 1)因为偶尔会给3,这是一个越界索引.

这个公式:

r.nextInt(max - min + 1) + min
Run Code Online (Sandbox Code Playgroud)

是在适当的时候minmax都需要被包括在随机整数的产生范围.当所需范围达到但不包括时max,公式应为:

r.nextInt(max - min) + min
Run Code Online (Sandbox Code Playgroud)

我的建议是使用它,但分别用0和3代替minmax.

您也可以考虑移动magictextr移出方法,并使它们成为类的成员字段.您可以对该text字段执行相同的操作,因此您不需要每次都查找它.您可以textonCreate方法中初始化该字段.您的代码将如下所示:

private final Random r = new Random();
private final String[] magictext = {"yes", "no", "maybe"};
private TextView text;

protected void onCreate(Bundle savedInstanceState) {
    . . . // what you have now, followed by
    text = (TextView) findViewById(R.id.textView1);
}

public void magicbegins()
{
    int rand = r.nextInt(magictext.length);

    text.setText(magictext[rand]);
}
Run Code Online (Sandbox Code Playgroud)