Android Random string generated from int
Basically Im trying to generate a random string when the page loads up. The problem is I dont know how to make the created random integer as a variable for my switch case. Can anyone modify my code and help me?
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 ChooseA开发者_如何学运维ctivity() {
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>
You shouldn't switch on random, you should first get an int:
Random rand = new Random();
int myRandom = rand.nextInt() % 3;
or, as you implemented it
Random myRandom = new Random();
//...
switch(myRandom.nextInt() %3) {
In your code, you have myRandom.nextInt(2))
. This will generate 0 or 1, but in your switch you check for values of 0, 1 or 2. I assume you want one of these values.
Random myRandom = new Random();
int randomNumber = myRandom.nextInt(3);
TextView textGenerateNumber = (TextView) findViewById(R.id.generatenumber);
textGenerateNumber.setText(String.valueOf(randomNumber));
精彩评论