使用random()时如何打印数组索引

时间:2016-04-26 21:37:41

标签: java arrays random

我的代码存在问题。它应该填充一个包含5个单词的数组列表。然后生成一个随机数,用于根据索引从数组列表中选择一个单词。我遇到的问题是当我尝试打印随机数时,它与显示的单词的索引不匹配。

/*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)

1 个答案:

答案 0 :(得分:0)

您的打印行应如下所示。

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

您可以在打印前找到索引。所以你可以在打印线内使用它。打印时无需再次找到它......