Java Choice Maker

by mohamede.elkarem in Circuits > Software

1692 Views, 2 Favorites, 0 Comments

Java Choice Maker

Screenshot (8).png

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

Screenshot (8)_LI.jpg

Import the scanner and Random classes in java

import java.util.Scanner;

import java.util.Random;

Setting Up a Main Method

Screenshot (9)_LI.jpg

Set up a main function in java

public static void main(String[] args) { }

Declaring the Scanner

Screenshot (10)_LI.jpg

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

Screenshot (11)_LI.jpg

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

Screenshot (12)_LI.jpg

Initialize an array with as many elements as you have choices in this case stringArray

String[] stringArray= new String[numChoices+1];

Making the Loop

Screenshot (15)_LI.jpg

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

Screenshot (16)_LI.jpg

Use the scanner to input your choices into the array

stringArray[i]= scanner.nextLine();

Declaring Random

Screenshot (17)_LI.jpg

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

Screenshot (18)_LI.jpg

Generate a random number using rand and assign it a variable in this case randomChoice

int randomChoice= rand.nextInt(numChoices);

Printing the Choice

Screenshot (19)_LI.jpg

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!