-1

I am making a sort of simple calculator. It needs to print 2 random numbers, add or subtract them. For ex. it would print 3422-193 or 3422+193. The user then answers the question and it says whether they are right or wrong.

I haven't tried much as I'm new to coding, so I don't know where to start. mport java.util.Random; import java.util.Scanner;

public class MathTutor {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);


    int useranswer;
    int answer; 


    Random rand = new Random(); 

    int n1 = rand.nextInt(9999) + 1;
    int n2 = rand.nextInt(999) + 1; 

    int operator = (int) (2 * Math.random() + 1);


    if (operator == 1) { 
        answer = n1 + n2;
        System.out.println("n1 + n2" + "=  ? "); 

    } else if (operator == 2) { 
        answer = n1 - n2;
        System.out.println("n1 - n2" + "= ?"); 

    useranswer = scanner.nextInt(); 

    if (useranswer == answer) {
        System.out.println("You are right."); 

    } else if (useranswer > answer) {
        System.out.println("Incorrect. Your answer is too high. Answer is " + answer); 

    } else if (useranswer < answer) {
        System.out.println("Incorrect. Your answer is too low. Answer is " + answer);           
    }

    }

}

}

When I run the code, it displays the equation correctly. The only thing is, it displays n1 - n2 = ? OR n1 + n2 = ?. What do I do to get this to display random numbers instead of n1 and n2?

1 Answers1

0

You need to decalre your variable:

int operator;

P.S. you also seem to have forgotten to close the curly braces after

   } else if (operator == 2) { 
        answer = n1 - n2;
        System.out.println(n1 - n2 + "= ");
Shloim
  • 5,281
  • 21
  • 36
  • I fixed the variable issue, but now it is saying Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive at java.base/java.util.Random.nextInt(Random.java:388) at MathTutor.main(MathTutor.java:25) – Kevin Morrow Jr. Sep 25 '19 at 14:26
  • operator is 0. rand,nextInt does not accept non positive values – Shloim Sep 25 '19 at 14:30
  • Ok, now I have it displaying 2 numbers and an equation, but the numbers aren't actually numbers. They are n1 - n2 =? How do I fix this so that it displays two numbers instead of n1, n2? – Kevin Morrow Jr. Sep 25 '19 at 15:12