按钮的字符串数组列表中的随机文本

时间:2013-06-18 08:22:49

标签: android

示例我有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" />

并且我有来自arraylist的文本随机代码:

final String[] answers = private static final String[] answers = {"a", "b", "c", "Vowel", "d", "e", "f", "Vowel"};

Bellow是来自arrayList的代码get“Vowel”文本:

final ArrayList<Integer> numbers = new ArrayList<Integer>();
    Random rnd = new Random();
    while (numbers.size()<=4)
    {
      int randomInteger = rnd.nextInt(answers.length);
      if (!numbers.contains(randomInteger))
      {
        numbers.add(randomInteger);
      }
    }
    if (!numbers.contains(3))
    {// here 3 is index of vowel
        int index = rnd.nextInt(numbers.size());//this random to set the index of vowel at random position
        numbers.set(index,3);
    }

    final Button q1 = (Button) findViewById(R.id.q1);
    q1.setText(answers[numbers.get(0)]);

    final Button q2 = (Button) findViewById(R.id.q2);
    q2.setText(answers[numbers.get(0)]);

    final Button q3 = (Button) findViewById(R.id.q3);
    q3.setText(answers[numbers.get(0)]);

以上代码在活动开始时一直显示元音...但有时元音显示为双,因为在ArrayList中有2个“元音”:

(Not correct)Example 5 times to start acivity:

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

那么,如何在数组列表中只显示1个“元音”事件有2个“元音”:

(Correct) Example 5 times to start acivity:

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

上面的代码完全没有错误...有时它会显示2个“元音”..但我想只显示1个元音。

如何修改它?

由于

1 个答案:

答案 0 :(得分:0)

你正在检查索引3,因为它是元音的索引但是索引7怎么样?这也是元音。

if (!numbers.contains(3) && !numbers.contains(7))
    {// here 3 is index of vowel
        int index = rnd.nextInt(numbers.size());//this random to set the index of vowel at random position
        numbers.set(index,3);
    }