The idea behind an 8-Ball is very simple. You ask the eight ball a yes or no question, and it tells you the answer.

Except, that the answer it choses is randomly selected from a set of prefabricated responses.

A real life 8-Ball

Write a program that continuously prompts the user for a yes or no question, and then randomly selects from 5 canned answers:

  • Without a doubt.
  • Yes.
  • Ask again later.
  • No.
  • Karel thinks so.

Here is an example run of the program.

To generate random numbers create a RandomGenerator instance variable (a variable declared outside all methods) like so:

private RandomGenerator rgen = new RandomGenerator();

You can then use the variable to generate random numbers.

rgen.nextInt(max) //generates a random int in the range [0, max)

Solution

/**
 * Class: Eight Ball
 * -----------------
 * Simulates an eight ball and gives sage answers to yes or
 * no questions.
 */
public class EightBall extends ConsoleProgram {
    
    private static RandomGenerator rg = new RandomGenerator();
    
    public void run() {
        while(true) {
            readLine("Ask a yes or no question: ");
            
            int choice = rg.nextInt(5);
            println(choice);
            if(choice == 0) {
                println("Without a doubt");
            }
            if(choice == 1) {
                println("Yes");
            }
            if(choice == 2) {
                println("Ask again later.");
            }
            if(choice == 3) {
                println("No");
            }
            if(choice == 4) {
                println("Karel thinks so.");
            }
            println("");
        }
    }
}
X