In the famous Magic 8-Ball toy, the user asks a question, and the device respond
ID: 3751586 • Letter: I
Question
In the famous Magic 8-Ball toy, the user asks a question, and the device responds with a randomly selected answer (see http://en.wikipedia.org/wiki/Magic_8-Ball for more details). Write a program that asks the user for a question and displays one of three equally probable answers. To get a sentence from the user, use the nextLine() method. (Note that the question will be ignored, but the user does not know this!) To randomly generate a 0, 1, or 2, use the following expression as explained in lecture.
For efficiency, use nested “if-else” statements to check the value of number to determine which message to display. Do not use three separate “if” statements. Below are examples of how your output might look (user input in bold). You may use any messages you wish.
Example A:
What is your question? Can I go home now?My sources say no.
Example B:
What is your question? Are you reliable?Cannot predict now.
Explanation / Answer
Code:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner in =new Scanner(System.in);
//Ask user to input
System.out.println("What is your Question?");
//Read from console
String str=in.nextLine();
//Generate random number from 0,1,2
int number =(int)(Math.random()*3);
//If random number generated is 0 print this
if(number==0)
System.out.println("Now it's your time");
//If random number generated is 1 print this
else if(number==1)
System.out.println("Arise awake and stop not till goal is achieved");
//else random number generated is 2 print Boom Boom
else
System.out.println("Boom Boom");
}
}
Output:
What is your Question?
Can I go home now
Now it's your time
//Output will be random from case 1 case 2 and case 3