Im currently trying to run a program that has the user input a number and have the program select the word. However I can't seem to get the program to function right. I am able to have the program run without having the index changed. Is there something I am missing here? I've imported the Random function but am having trouble figuring out the last part. All this is being done in NetBeans.
package arraywords;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class Arraywords {
public static void main(String[] args) {
ArrayList<String>words = new ArrayList();
words.add("Token");
words.add("Magic");
words.add("People");
words.add("Racecar");
words.add("Xbox");
words.add("Puppy");
words.add("Destiny");
words.add("Knowledge");
words.add("Home");
words.add("Professional");
System.out.print("Choose a random number between 1 and 10 "
+ "to recieve a random word:\n");
int choice = 0;
Scanner scanner = new Scanner(System.in);//Scanner program
while (choice < 1 || choice > 10) {//The parametors for the users
System.out.println("Input a number:");
String message = scanner.next();//Prompt for user to input a number
try{
choice = Integer.parseInt(message);
}
catch(NumberFormatException e){
System.out.print("Please use numbers");
} /* The while loop watches the users input and is waiting for the user to input a number. Once they select a number. The word should be displayed. */
}
Integer index = choice -1; /* Since arrays begin with zero I had to account for that by adding the -1. */
System.out.printf("You entered #%d:\n> %s.", choice, words.get(index)); //Once the user has chosen a number the word will be displayed
}
}