How to randomise the characters '+' and '-' in java

落爺英雄遲暮 提交于 2021-02-08 12:13:33

问题


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.");
            }

        }
    }

回答1:


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:

/



回答2:


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




回答3:


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.




回答4:


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));


来源:https://stackoverflow.com/questions/64592115/how-to-randomise-the-characters-and-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!