So, I'm trying to write a program for a Magic 8-ball program in Java. I need to use math.Random() to generate responses, use a while loop to take questions and get responses, then log the questions and predictions into a .txt file.
I have everything that I wrote here, though I can't seem to quite figure out why the random number generator is generating the same number over and over again. It does generate one, but what I need is something that will generate multiple random numbers. Also, my printwriter isn't logging the questions into the .txt file.
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
}
}