所以,我正在尝试用Java编写一个Magic 8-ball程序。我需要使用math.Random()来生成响应,使用while循环来获取问题并获得响应,然后将问题和预测记录到.txt文件中。
我有我在这里写的所有内容,但我似乎无法弄清楚为什么随机数生成器一遍又一遍地生成相同的数字。它确实产生了一个,但我需要的是能产生多个随机数的东西。另外,我的printwriter没有将问题记录到.txt文件中。
public class Magic8Ball {
public static void main(String[] args) {
boolean questionAsked = false;
String question = "Please ask a question and make sure to add a ? (X to quit):";
String response = getPrediction();
String filename = "src/predictions.txt";
String sentinel = "x";
Scanner scnr = new Scanner(System.in);
//variables needed
PrintWriter out = null;
//Printwriter
try {
out = new PrintWriter(filename);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
//try-catch statement
while (!questionAsked) {
System.out.println(question);
String input = scnr.nextLine();
out.println(input);
//Log questions
if (input.contains("?")) {
System.out.println(response);
out.println(response);
//Log predictions
}
else if (input.equalsIgnoreCase(sentinel)) {
questionAsked = true;
System.out.println("Have a nice day!");
}
else {
System.out.println("Please try again.");
}
}
//Main process (Ask questions and get predictions)
}
public static String getPrediction () {
//getPrediction() method for the predictions
int randomNum = (int) (Math.random()* 10) + 1;
//Get a random number
/*Error: Keeps the same number for all the responses until you
restart the program. Need to figure out how to make it restart
right away.
*/
String response[] = new String[10];
response[0] = "It is certain";
response[1] = "As I see it, yes";
response[2] = "Reply hazy try again";
response[3] = "Don't count on it";
response[4] = "Without a doubt";
response[5] = "Cannot predict now";
response[6] = "Ask again later";
response[7] = "Very doubtful";
response[8] = "Signs point to yes";
response[9] = "You may rely on it";
//List of responses
String answer = response[randomNum];
return answer;
//Returns a string from the array to the main method
}
}