Good evening.
I am writing a program which allows the user to input their name and then answer ten questions that take the form "1 + 2 = ?", where the ? is, of course, the answer to be given. The numbers and operator - add or subtract - are to be generated at random. I have almost completed the program, but the real stumbling block right now is knowing what to do for the random operator; I have tried using a switch statement, but that didn't work for some reason (although whether I did it right or not is another matter entirely), and I don't know what else to try.
Below is what I've done so far:
import java.util.Scanner; import java.util.Random; public class MathsQuestions { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String user; System.out.print("What is your name? "); user = scan.nextLine(); System.out.println("Hello " + user + ", let's begin."); playGame(); System.out.println("Thank you for playing; hope to see you again soon!"); } public static void playGame() { Random rand = new Random(); Scanner answer = new Scanner(System.in); int count = 1; int score = 0; int firstNumber = rand.nextInt(8) + 11; int secondNumber = rand.nextInt(9) + 1; int userAnswer; char operator = rand.nextBoolean() ? '+' : '-'; while(count <= 10) { System.out.print(count + ". " + firstNumber + operator + secondNumber + " = "); userAnswer = answer.nextInt(); if (userAnswer == rightAnswer) { System.out.println("Correct!"); count++; score++; } else { System.out.println("Incorrect - right answer is " + rightAnswer + "."); count++; } } if (score == 10) { System.out.println("You scored " + score + " - excellent!"); } else if (score > 5) { System.out.println("You scored " + score + " - good job."); } else if (score > 1) { System.out.println("You scored " + score + " - you need to try harder."); } else { System.out.println("You scored " + score + " - it'd be worth getting extra help."); } } }
I would appreciate any help I can get, as this is becoming quite frustrating...
Regards.