java 需要帮助制作随机数学生成器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17358255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:47:18  来源:igfitidea点击:

Need help making a random math generator

javanetbeans

提问by user2530677

What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”

我应该做的是:编写一个程序,给用户 10 道随机数学问题,每次都询问答案,然后告诉用户他们是对还是错。每个问题应使用 1 到 20 之间的 2 个随机数,以及一个随机运算(+、-、* 或 /)。您将需要重新随机化每个数学问题的数字。您还应该跟踪他们做对了多少问题。最后,告诉用户他们做对了多少问题,并根据他们的结果给他们一条消息。例如,您可以说“干得好”或“您需要更多练习”。

So far I am at a loss

到目前为止我不知所措

import java.util.Scanner; 

public class SS_Un5As4 {

 public static void main(String[] args){

 Scanner scan = new Scanner(System.in);

 int number1 = (int)(Math.random()* 20) + 1;

int number2 = (int)(Math.random()* 20) + 1;

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

  if (operator == 1)

  System.out.println("+"); 

 if (operator == 2) 

   System.out.println("-");

 if (operator == 3)

 System.out.println("*");

  if (operator == 4)
            System.out.println("/");  


      }
  }

I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.

我主要需要知道如何将这些随机数和运算符变成问题,以及如何对每个问题进行评分以查看它们是否错误。

回答by petajamaja

Well, what you need to add is:

那么,你需要补充的是:

  • to count answers:

    • a variable that counts correct answers (increment it every time the user answers correctly);
    • a variable to store current correctanswer;
    • a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
    • a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
  • to create a problem:

    • put problem generation and answer evaluation into a cycle, which repeats 10 times;
    • in your switch (i.e. when you choose operators) also calculate the correct answer:

       switch(operator){
      
            case 1: {
            operation = "+";
            correctResult = number1 + number2;
            break;
         }
         case 2: ....
         case 3: ....
         case 4: ....
         default: break;
      }
      
    • don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
  • 计算答案

    • 一个计算正确答案的变量(每次用户正确回答时递增);
    • 存储当前正确答案的变量;
    • 一个存储当前用户答案的​​变量(每下一个问题刷新它,不需要永远存储它,因为在你的情况下只需要统计数据);
    • 一个函数(让它被称为例如 gradeTheStudent() )它使用几个条件来决定根据正确答案的数量打印什么;
  • 制造问题

    • 将问题生成和答案评估放入一个循环中,重复10次;
    • 在您的开关中(即当您选择运算符时)还计算正确答案:

       switch(operator){
      
            case 1: {
            operation = "+";
            correctResult = number1 + number2;
            break;
         }
         case 2: ....
         case 3: ....
         case 4: ....
         default: break;
      }
      
    • 不要忘记检查用户是否输入了数字或其他内容(您可以使用异常或简单条件)。

So, a "pseudocode"solution for your problem would look something like this:

因此,针对您的问题的“伪代码”解决方案如下所示:

  String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
  num1 = 0
  num2 = 0
  operator = NIL
  userScore = 0
  userAnswer = 0
  correctAnswer = 0

  def function main:

      counter = 0
      for counter in range 0 to 10:
          generateRandomNumbers()
          correctAnswer = generateOperatorAndCorrectAnswer()
          printQuestion()
          compareResult()

      gradeStudent()

  def function generateRandomNumbers:
      # note that you have already done it!

  def function generateOperatorAndCorrectAnswer:
      # here goes our switch!
      return(correctAnswer);

  def function printQuestion:
      print  "Next problem:" + "\n"
      print num1 + " " + operator + " " + num2 + " = " + "\n"

  def function compareResult(correctAnswer):
      # get user result - in your case with scanner
      if(result == correctAnswer) 
                print "Great job! Correct answer! \n"
                userScore++
      else print "Sorry, answer is wrong =( \n"

  def function gradeStudent (numOfCorrectAnswers):
      if(numOfCorrectAnswers >= 7) print reactions[0]
      else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
      else print reactions[2]

General advice:don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.

一般建议:不要试图一次性解决所有问题。一个好的方法是创建小函数,每个函数都做自己独特的任务。问题分解也是一样:你只需要写下你认为你需要的东西来模拟情况,然后一步一步地做。

Note:as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.

注意:从你目前的功能来看,你对Java中的面向对象编程并不熟悉。这就是为什么我没有提供任何关于使用类的好处的提示。但是,如果你是,那么请告诉我,我会在我的帖子中添加信息。

Good luck!

祝你好运!

回答by demi

For example you can use something like that:

例如,您可以使用类似的东西:

public class Problem {
    private static final int DEFAULT_MIN_VALUE = 2;
    private static final int DEFAULT_MAX_VALUE = 20;

    private int number1;
    private int number2;
    private Operation operation;

    private Problem(){
    }

    public static Problem generateRandomProblem(){
        return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
    }

    public static Problem generateRandomProblem(int minValue, int maxValue){
        Problem prob = new Problem();
        Random randomGen = new Random();

        int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
        int number2 = randomGen.nextInt(maxValue + minValue) + minValue;

        prob.setNumber1(number1);
        prob.setNumber2(number2);

        int operationCode = randomGen.nextInt(4);
        Operation operation = Operation.getOperationByCode(operationCode);
        prob.setOperation(operation);

        return prob;
    }

    public int getNumber1() {
        return number1;
    }

    public int getNumber2() {
        return number2;
    }

    public Operation getOperation() {
        return operation;
    }

    public void setNumber1(int number1) {
        this.number1 = number1;
    }

    public void setNumber2(int number2) {
        this.number2 = number2;
    }

    public void setOperation(Operation operation) {
        this.operation = operation;
    }
}

And another class for holding operations:

另一个用于保持操作的类:

public enum Operation {
    PLUS,
    MINUS,
    MULTIPLY,
    DIVIDE;

    public double operationResult(int n1, int n2) {
        switch (this) {
            case PLUS: {
                return (n1 + n2);
            }
            case MINUS: {
                return n1 - n2;
            }
            case MULTIPLY: {
                return n1 * n2;
            }
            case DIVIDE: {
                return n1 / n2;
            }
        }
        throw new IllegalArgumentException("Behavior for operation is not specified.");
    }

    public static Operation getOperationByCode(int code) {
        switch (code) {
            case 1:
                return PLUS;
            case 2:
                return MINUS;
            case 3:
                return MULTIPLY;
            case 4:
                return DIVIDE;
        }
        throw new IllegalArgumentException("Operation with this code not found.");
    }
}

But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.

但您不必抛出 IllegalArgumentException,还有其他选项可用于处理意外参数。

回答by Qben

Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.

由于我不想向您提供此问题的完整解决方案,而且您似乎对 Java 语言有一些了解,因此我将写下我将如何继续/更改您所拥有的内容作为开始。

First I would store the result in your operator if statements. Result is an int.

首先,我会将结果存储在您的运算符 if 语句中。结果是一个整数。

if (operator == 1) {
   operation="+";
   result=number1+number2;
}

After this I would print the math question and wait for the user to answer.

在此之后,我将打印数学问题并等待用户回答。

System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine();      // Read one line from the console.
in.close(); // Not really necessary, but a good habit.

At this stage all you have to do is compare the result with the user input and print a message.

在这个阶段,您所要做的就是将结果与用户输入进行比较并打印一条消息。

if(Integer.parseInt(userResult) == result) {
  System.out.println("You are correct!");
} else {
  System.out.println("This was unfortunately not correct.");
}

This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.

这个解决方案或多或少是伪代码,并且缺少一些错误处理(例如,如果用户在答案中输入测试),我也会将其拆分为方法,而不是将其全部放在 main() 中。下一步是使其面向对象(看看来自 demi 的答案)。祝你完成你的程序好运。

回答by Phill

In regard to generating random math operations with +, -, * & / with random numbers your can try the following;


import java.util.*;
public class RandomOperations{
   public static void main(String[] args){

       Random `mathPro` = new Random();
       //for the numbers in the game
       int a = mathPro.nextInt(50)+1;
       int b = mathPro.nextInt(50)+1;

       //for the all the math operation result

       int add = a+b;
       int sub = a-b;
       int mult = a*b;
       int div = a/b;
       //for the operators in the game

       int x = mathPro.nextInt(4);

       /*
         -so every random number between 1 and 4 will represent a math operator

         1 = +
         2 = -
         3 = x
         4 = /

      */

       if(x == 1){

          System.out.println("addition");
          System.out.println("");
          System.out.println(a);
          System.out.println(b);
          System.out.println(add);

       }else if(x == 2){

          System.out.println("subtraction");
          System.out.println("");
          System.out.println(a);
          System.out.println(b);
          System.out.println(sub);

       }else if(x == 3){

          System.out.println("multiplication");
          System.out.println("");
          System.out.println(a);
          System.out.println(b);
          System.out.println(mult);

       }else{

          System.out.println("division");
          System.out.println("");
          System.out.println(a);
          System.out.println(b);
          System.out.println(div);

       }
  //This os for the user to get his input then convert it to a numbers that the program can
  //understand
       Scanner userAnswer = new Scanner(System.in);
               System.out.println("Give it a try");
                 int n = `userAnswer.nextInt();

回答by user11011990

Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions Code :

打印数字和操作,使用文件 IO 读取用户输入,并执行跟踪已回答问题的逻辑代码:

public class SS_Un5As4 {

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);
        int number1 = (int)(Math.random()* 20) + 1;
        int number2 = (int)(Math.random()* 20) + 1;
        int operator = (int)(Math.random()*4) + 1;
        String operation = null;
        if (operator == 1)
            operation="+";      
        if (operator == 2) 
                operation="-";  
        if (operator == 3)
            operation="*";  
        if (operator == 4)
            operation="/";    
        System.out.println("Question "+number1+operation+number2);


    }
}

Keep a track of result and compare with the user input and verify its right or wrong

跟踪结果并与用户输入进行比较并验证其正确或错误

public static void main(String[] args) throws IOException{

public static void main(String[] args) 抛出 IOException{

    int number1 = (int)(Math.random()* 20) + 1;
    int number2 = (int)(Math.random()* 20) + 1;
    int operator = (int)(Math.random()*4) + 1;
    String operation = null;
    int result=0;
    if (operator == 1){
        operation="+";
        result=number1+number2;
    }
    if (operator == 2) {
        operation="-";
        result=number1-number2;
    }
    if (operator == 3){
        operation="*";  
        result=number1*number2;
    }
    if (operator == 4){
        operation="/";
        result=number1/number2;
    }
    System.out.println("Question "+number1+operation+number2);
    String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
    if(result==Integer.parseInt(result1))
        System.out.println("Right");
    else
        System.out.println("Wrong");
}