0

我想将按钮的文本设置为随机字母我使用了按钮的设置文本属性并传递了包含随机字母的变量

 import java.util.Random;

 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;

 public class OnePlayerEasy extends Activity {
char z;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.oneplayereasy);

}

public void gen(View v) {
    Random r = new Random();

    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < 1; i++) {
        z = alphabet.charAt(r.nextInt(alphabet.length()));
        Button button = (Button)findViewById(R.id.button1);//button i want               to genrate random no on
        button.setText(z);
    } // prints random characters


}
 }
4

2 回答 2

0

在这里你可以做什么:

public class OnePlayerEasy extends Activity {
char z;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.oneplayereasy);
    Button button = (Button)findViewById(R.id.button1);
    button.setText(gen());

}
   public String gen() {
    Random r = new Random();
    char z = 0;
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < 1; i++) {
        z = alphabet.charAt(r.nextInt(alphabet.length()));
    } // prints random characters
    return String.valueOf(z);
}
}
于 2013-05-29T06:00:33.220 回答
0

我知道您想为按钮标题设置随机字符,如果我是对的,请尝试以下代码

int min = 0;
int max = 25;
Random r = new Random();
int randomIndex = r.nextInt(max - min + 1) + min;
Button button = (Button)findViewById(R.id.button1);
button.setText(alphabet.charAt(randomIndex));

如果您想随机播放字母并将所有字符设置为按钮,请尝试下一件事

ArrayList<Character> chars = new ArrayList<Character>(alphabet.length());
for ( char c : alphabet.toCharArray() ) {
   chars.add(c);
}
Collections.shuffle(chars);
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
   shuffled[i] = chars.get(i);
}
String shuffledWord = new String(shuffled);
button.setText(shuffledWord);

第二个会给你打乱的字母

于 2013-05-29T06:01:27.763 回答