-2

I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:

Question 1: num1 + num2 =

or

Question 2: num1 - num2 = 

I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.

Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!

As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.

//prompt user to start the game
            System.out.println();
            System.out.print("Press y to Start the Game: ");
            String start_program = keyboard.next();
    
            if (start_program.equals("y")) {

heres my code so far:

public static void main(String[] args) {
        //mental arithmetic game
        System.out.println("You will be presented with 8 addition questions.");
        System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");

        //set up input scanner
        Scanner keyboard = new Scanner(System.in);


        //declare constant variables
        final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;

        long start_time, end_time;

        //generate 2 random numbers
        int random_number1 = (int) ((Math.random() * max_range) + min_range);
        int random_number2 = (int) ((Math.random() * max_range) + min_range);

        //declare variables
        int question_number = 1;
        int guess;


        //prompt user to start the game
        System.out.println();
        System.out.print("Press y to Start the Game: ");
        String start_program = keyboard.next();

        if (start_program.equals("y")) {


            //start timer
            start_time = System.currentTimeMillis();

            //ask the question
            System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
            //take in user input
            guess = keyboard.nextInt();


            while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
                System.out.println("Correct");
                ++question_number;
                //generate a new question
                //generate 2 random numbers
                random_number1 = guess;
                random_number2 = (int) ((Math.random() * max_range) + min_range);
                //ask the question again
                System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
                //take in user input
                guess = keyboard.nextInt();
            }
            end_time = System.currentTimeMillis();
            int time_taken = (int) (end_time - start_time);

            if (guess != (random_number1 + random_number2))
                System.out.println("Wrong");
            else {
                System.out.println();
                System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
            }

        }
    }
U Kushi
  • 17
  • 1
  • 5
  • 1
    There are many ways to do that. For example you can put the values into a List, and just shuffle that, and pick the first one ( https://www.geeksforgeeks.org/collections-shuffle-java-examples/ ) ... or you put them in an array, and pick a random number within the length of that array, and use the random value as index. – GhostCat Oct 29 '20 at 13:32
  • Get into the habit of initializing your scanner's delimiter: Immediately after `new Scanner`, do: `scanner.useDelimiter("\r?\n");`. Now you can ask for blank lines (`.next()` will then return an empty string), you need never bother with nextLine(), just call next() for a whole line. – rzwitserloot Oct 29 '20 at 13:51
  • Java naming conventions use camelCase rather than snake_case. That is, there are no underscores inside names for classes, methods, or variables. – NomadMaker Oct 29 '20 at 14:37
  • Does this answer your question? [How to randomly select one from two integers?](https://stackoverflow.com/questions/40311442/how-to-randomly-select-one-from-two-integers) – Joe Jan 05 '21 at 14:39

4 Answers4

5

You can use Random#nextInt to pick a random int from 0 to array.length - 1 which you can use as the index of an array of operators.

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        char[] operators = { '+', '-', '*', '/' };

        // Pick a random operator
        Random random = new Random();
        char op = operators[random.nextInt(operators.length)];

        System.out.println(op);
    }
}

A sample run:

/
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
3

I think for the random - and + characters you could use boolean like so:

Random rd = new Random(); // creating Random object
if(rd.nextBoolean()) { 
   //Do something 
} else { 
   //Do Something else
}

For the enter, i think this is a game that is played in the console of the ide? Because then you can use a Scanner to track when enter is being pressed. This will help you i think: Java using scanner enter key pressed

LorenzoOtto
  • 112
  • 8
1

The thing with the "Enter 'y' to start the game" is totally superfluous, as evidenced by the fact that you obviously don't have sensible things to do when the user does not enter 'y'.

So, since this is a command line application, why would anyone start it and then not want to play the game? Just go ahead and ask the first question! If the user did start that program by accident somehow, there will be no harm whatsoever, it's not that you're going to overwrite important files, start missiles or something like that.

Ingo
  • 36,037
  • 5
  • 53
  • 100
  • yeah, i agree with you here but it's part of a homework and the specifications state that you need to press enter to continue, not sure why but there you go. – U Kushi Oct 29 '20 at 14:03
  • I see. But "to continue" is not the same as "to start". You prompt the user, and when he enters 'y' you play one game. I guess what is wanted is: you play a game, then ask if the user wants another one, and when the answer is 'y', start over. – Ingo Oct 29 '20 at 23:24
0

You could try something like this.

Random r = new Random();
int[] signs = { 1, -1 };
char[] charSigns = { '+', '-' };

int a = r.nextInt(20);
int b = r.nextInt(20);
int sign = r.nextInt(2);

System.out.printf("%s  %s  %s = ?%n", a, charSigns[sign], b);

// then later.

System.out.printf("The answer is " + (a + signs[sign] * b));
WJS
  • 36,363
  • 4
  • 24
  • 39