【解決方法】このリストから 1 つのアイテムを返すには?


リストから 1 つの項目を選択して返すには、Random の nextInt メソッドを使用する必要があります。 リストのサイズに関係なく、リスト内の任意の文字列を返すメソッドが必要です。 ただし、リストには常に少なくとも 1 つの項目が含まれます。

私が試したこと:

これが現時点での私のメソッドですが、変数の選択がこのメソッドで既に定義されており、変数 ArrayList と String が宣言されていないというエラーが表示されます。

Java
<pre>/**

* Return a random one of the strings in the given list.

* The list will have at least one item in it.

* @param choices A list of strings.

* @return One of the strings in the given list.

*/

public String chooseOne(ArrayList<String> choices)

{

Random rand = new Random();

ArrayList<String>choices;

return rand.nextString(ArrayList<String>choices);

解決策 1

これに少し注釈を付けることができるかどうか見てみましょう:

Java
public String chooseOne(ArrayList<String> choices) {
    Random rand = new Random();
    // Up to this point, all is good.
    ArrayList<String> choices;  // Error: this attempts to define a new choices variable
    // but we already have a choices variable defined in the parameter list
    return rand.nextString(ArrayList<String> choices);
    // Error:  There is no nextString method for a rand object.
}

とすれば ArrayList.size() リスト内の要素の数を返し、 rand.NextInt(int bound) 範囲内の次の整数を返します (0 .. 境界)。コードを修正する方法を理解できるはずです。

コメント

タイトルとURLをコピーしました