2016-04-26 1 views
0

私のコードに問題があります。配列リストに5つの単語を設定することになっています。乱数が生成され、そのインデックスに基づいて配列リストから単語を選択するために使用されます。私が抱えている問題は、表示されている単語のインデックスと一致しない乱数を印刷しようとするときです。random()を使用している場合の配列インデックスの印刷方法

/*This program will prompt the user to enter 5 words. 
These messages will be stored in a ArrayList. 
The program will then number the messages and display them in a list. 
The program will then generate a random number. 
The program will then use the random number to display a word from the ArrayList.*/ 

package wordup; 

import java.util.ArrayList; 
import java.util.Scanner; 
import java.util.Random; 

public class WordUp { 

/* @param args the command line arguments */ 

public static void main(String[] args) { 
    // TODO code application logic here 

    ArrayList<String> words = new ArrayList<>(); 
    for (int i = 0; i < 5;i++) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter a word."); 
     words.add(i, input.nextLine()); 
    } 
    for (int i = 0; i < words.size(); i++) { 

     System.out.println((i)+". "+words.get(i)); //Should print the messages 
    } 

    Random word = new Random(); 
    int index = word.nextInt(words.size()); 
    System.out.println("Your randomly generated word is: " +words.get(word.nextInt(words.size()))+"."); 
    System.out.println("It was found at index " +index+"."); 
} 

} 

は例えば、私が手出力は次のように

run: 
Enter a word. 
a 
Enter a word. 
b 
Enter a word. 
c 
Enter a word. 
d 
Enter a word. 
e 

0. a 
1. b 
2. c 
3. d 
4. e 

Your randomly generated word is: c. 
It was found at index 0. 
BUILD SUCCESSFUL (total time: 7 seconds) 
+2

「Random.nextInt()」を呼び出すたびに、別のランダム値が生成されます。この例では、 'word.nextInt()'を2回呼び出します.1回は 'index'に割り当て、1回はwordを選択します。これは、選択された単語がインデックスと一致しない理由を説明します。 – gudok

+0

単語の選択に使用した番号を印刷するには、何を変更する必要がありますか? – msaito

+0

'System.out.println("無作為に生成された単語は "+ words.get(index)+"。 ");' – gudok

答えて

0

あなたの印刷ラインがなければなりません。

int index = word.nextInt(words.size()); 
    System.out.println("Your randomly generated word is: " + words.get(index) + "."); 

インデックスは印刷の直前にあります。だからあなたは印刷ラインの中でそれを使うことができます。印刷時に再度検索する必要はありません。

関連する問題