1

示例我有 3 个按钮

<Button
    android:id="@+id/q1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/q2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/q3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

我有如下随机文本

private static final String[] answers = {"a", "b", "c", "Vowel", "d", "e", "f"};
String q = answers[rgenerator.nextInt(answers.length)];
button1.setText(q);
button2.setText(q);
button3.setText(q);

示例我随机开始活动 5 次:

1st activity start random look like: a, c, Vowel
2st activity start random look like: b, Vowel, a
3st activity start random look like: Vowel, e, b
4st activity start random look like: a, e, Vowel
5st activity start random look like: Vowel, b, f

在活动刷新/开始时,所有时间活动开始必须始终将“元音”setText 设置为 3 个按钮中的 1 个。

我真的坚持下去了..

4

2 回答 2

7

你可以试试这两种情况:

 ArrayList<Integer> numbers = new ArrayList<Integer>();
 boolean vowel_added = false;
    Random rnd = new Random();
    while (numbers.size()<=3) {
      int randomInteger = rnd.nextInt(answers.length());
      if (!numbers.contains(randomInteger)) {

            if (answers[randomInteger]).equalsIgnoreCase("Vowel"))
             {
                 if (! vowel_added)
                 {
                   vowel_added = true;
                   numbers.add(randomInteger);
                 }
             }
             else
             {
                 numbers.add(randomInteger);
             }
       }
    }
    if (! vowel_added) {
      int index = rnd.nextInt(numbers.size());//this random to set the index of vowel at random position
      numbers.set(index,3);//you can find the index of one vowel and put here
    }
    button1.setText(answers[numbers.get(0)]);
    button2.setText(answers[numbers.get(1)]);
    button3.setText(answers[numbers.get(2)]);

希望这可以帮助

于 2013-06-18T05:12:30.717 回答
0
int firstRandomNum  = (int)(Math.random()*6);  // Generate Random Number
int secondRandomNum = (int)(Math.random()*6);  // Generate Random Number

int indexOfVowel = 3; // As you said one text must be Vowel , its index is 3

Button b1 = (Button)findViewById(R.id.q1);
Button b2 = (Button)findViewById(R.id.q2);
Button b3 = (Button)findViewById(R.id.q3);
if(firstRandomNum != indexOfVowel && secondRandomNum != indexOfVowel ) {

 b1.setText(""+answers[firstRandomNum]);
 b2.setText(""+answers[secondRandomNum ]);
 b3.setText(""+answers[indexOfVowel]);
} else {
    b1.setText(""+answers[firstRandomNum]);
    b2.setText(""+answers[secondRandomNum ]);
    b3.setText(""+answers[indexOfVowel+1]);
}

上面的代码只是为了帮助你,它不是完整的逻辑或没有错误

于 2013-06-18T04:33:45.817 回答