mardi 26 avril 2016

How to print array index when using random()

I'm having issues with my code. It's suppose to populate an array list with 5 words. A random number is then generated and used to pick a word from the array list based on it's index. The problem I'm having is when I try to print the random number it doesn't match the index of the word displayed.

/*This program will prompt the user to enter 5 words.
These messages will be stored in a ArrayLsit.
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+".");
}   

}




Aucun commentaire:

Enregistrer un commentaire