Random Number Generator in Java
I'm writing a program that will work like a magic 8 ball. It asks for a question and then prints a random response out of 20 that I've put in it. It doesn't show any errors in the coding, but when I run it the program works perfectly until the point where it would need to print the random response. This is a homework assignment so I'm not looking for someone to correct it, but I'm trying to figure out exactly how to get this to work. Thank you and I appreciate the help.
import java.util.Scanner;
public class MagicBall
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please type in a question: ");
double question = input.nextDouble();
int number = (int)(Math.random() * 20);
if (number == 0)
System.out.println("As I see it, yes");
if (number == 1)
System.out.println("It is certain");
if (number == 2)
System.out.println("It is decidedly so");
if (number == 3)
System.out.println("Most likely");
if (number == 4)
System.out.println("Outlook good");
if (number == 5)
System.out.println("Signs point to yes");
if (number == 6)
System.out.println("Without a doubt");
if (number == 7)
System.out.println("Yes");
if (number == 8)
System.out.println("Yes – definitely");
if (number == 9)
System.out.println("You may rely on it");
if (number == 10)
System.out.println("Reply hazy, try again");
if(number == 11)
System.out.println("Ask again later");
if (number == 12)
System.out.println("Better not tell you now");
if (number == 13)
System.out.println("Cannot predict now");
if (number == 14)
System.out.println("Concentrate and ask again");
if (number == 15)
System.out.println开发者_开发问答("Don't count on it");
if (number == 16)
System.out.println("My reply is no");
if (number == 17)
System.out.println("My sources say no");
if (number == 18)
System.out.println("Outlook not so good");
if (number == 19)
System.out.println("Very doubtful");
}
}
double question = input.nextDouble();
What makes you think the question would be a floating point number?
Apache commons is very helpfull:
RandomUtils.nextInt(maxVal);
Your code works for me, but it forces you to input a double (e.g. 123.456). You should change:
double question = input.nextDouble();
to:
String question = input.nextLine();
Also, you may want to use a switch statement instead of all those ifs.
Instead of int number = (int)(Math.random() * 20);
Replace with int number = new Random().nextInt(20);
See http://download.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextInt(int)
精彩评论