我正在编写一个像魔术8球一样的程序。它询问一个问题,然后打印出20个我随机输入的随机响应。它没有显示编码中的任何错误,但是当我运行它时,程序完美地工作,直到它需要打印随机响应。这是一项家庭作业,所以我不是在寻找有人来纠正它,但我正在努力弄清楚如何让它发挥作用。谢谢,我感谢你的帮助。
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");
}
}
答案 0 :(得分:6)
double question = input.nextDouble();
是什么让你认为问题是浮点数?
答案 1 :(得分:2)
Apache commons非常有帮助:
RandomUtils.nextInt(maxVal);
答案 2 :(得分:1)
您的代码适用于我,但它会强制您输入双精度(例如123.456)。你应该改变:
double question = input.nextDouble();
为:
String question = input.nextLine();
此外,您可能希望使用switch语句而不是所有ifs。
答案 3 :(得分:0)
而不是int number = (int)(Math.random() * 20);
替换为int number = new Random().nextInt(20);
请参阅http://download.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextInt(int)