0

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

下面是从 arrayList 获取“元音”文本的代码:

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 个元音。

如何修改它?

谢谢

4

1 回答 1

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);
    }
于 2013-06-18T08:35:11.823 回答