从Int生成的Android随机字符串

时间:2011-06-02 10:53:49

标签: android string random int

基本上我试图在页面加载时生成随机字符串。问题是我不知道如何将创建的随机整数作为我的switch案例的变量。任何人都可以修改我的代码并帮助我吗?

CODE

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ask_2 extends Activity {

TextView ActivityNumber;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ask2);

    ChooseActivity();
}

private void ChooseActivity() {
    Random myRandom = new Random();
    TextView textGenerateNumber = (TextView) findViewById(R.id.generatenumber);
    textGenerateNumber.setText(String.valueOf(myRandom.nextInt(2)));
    TextView textGenerateDesc = (TextView) findViewById(R.id.generatedesc);
    switch (myRandom) {
    case 0:
        textGenerateDesc.setText("Hello0");
        break;
    case 1:
        textGenerateDesc.setText("Hello1");
        break;
    case 2:
        textGenerateDesc.setText("Hello2");
        break;
    }

}
}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Activity " />
<TextView android:id="@+id/generatenumber"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="Number" />
<TextView android:id="@+id/generatedesc" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Description" />

</LinearLayout>

2 个答案:

答案 0 :(得分:2)

你不应该随机打开,你应该首先得到一个int:

Random rand = new Random();
int myRandom = rand.nextInt() % 3;

或者,当你实施它时

Random myRandom = new Random();
//...
switch(myRandom.nextInt() %3) {

答案 1 :(得分:1)

在您的代码中,您有myRandom.nextInt(2))。这将生成0或1,但在您的开关中检查0,1或2的值。我假设您需要其中一个值。

Random myRandom = new Random();
int randomNumber = myRandom.nextInt(3);
TextView textGenerateNumber = (TextView) findViewById(R.id.generatenumber);
textGenerateNumber.setText(String.valueOf(randomNumber));