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)]);

上記のコードは、アクティビティの開始時に常にVowelを表示しています...しかし、ArrayListには2つの「Vowel」があるため、Vowelが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 はどうでしょうか。これもVowelです。

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 に答える