Java Choice Maker
This instruction set will show how to build a java program that will make a choice from a list of options that are input by the user. A basic working knowledge of java and an IDE to build the program in. Each step should take no more than 2 minutes.
Importing
Import the scanner and Random classes in java
import java.util.Scanner;
import java.util.Random;
Setting Up a Main Method
Set up a main function in java
public static void main(String[] args) { }
Declaring the Scanner
Initialize and declare a variable for the scanner in this case I named the variable scan
Scanner scan= new Scanner(System.in);
Number of Choices
Prompt the user for the number of choices.
Scanning for Number of Choices
Use the scanner object to input the number of choices and store in a variable in this case numChoices
int numChoices= scan.nextInt();
Initializing the Array
Initialize an array with as many elements as you have choices in this case stringArray
String[] stringArray= new String[numChoices+1];
Making the Loop
Write a for loop using a counter initialized to 0 to go through the array
for(int i=0; i< stringArray.length; i++ ){ }
Prompt Choices
Prompt User for the choices
Scan in the Choices
Use the scanner to input your choices into the array
stringArray[i]= scanner.nextLine();
Declaring Random
Declare variable for random in this case it is named rand (make sure to do this outside of the loop)
Random rand = new Random();
Generating a Random Number
Generate a random number using rand and assign it a variable in this case randomChoice
int randomChoice= rand.nextInt(numChoices);
Printing the Choice
Use the randomly generated number in to the array and print the element at that index
System.out.print(stringArray[randomChoice]);
Congratulations!
You should have a program that scans in a number of choices and prints out one of those choices at random.
If you are getting an array index out of bounds error check your loop counter. Make sure to check your code for proper semicolon use. remember that java is case sensitive!