【问题标题】:Create a simple math game using java objects使用 java 对象创建一个简单的数学游戏
【发布时间】:2019-08-14 15:23:09
【问题描述】:

我正在尝试使用 Java 对象创建一个简单的数学游戏。我的目标是创建一个问题类,其中包含一个用随机数显示问题的方法、一个检查答案的方法、一个问题结构。 如何使用这些对象生成 10 个随机问题?有加法、减法和乘法题。最后打印出正确答案的数量。

我已经创建了我的问题类,我的第一个方法使用变量“a”和“b”显示了一个随机问题。并存储答案。 我的第二种方法通过用户输入检查答案并打印结果。到目前为止,当我运行我的程序时,它只会一遍又一遍地显示相同的问题。

这是我的问题课

import java.util.*;

public class Question {
    private int a;
    private int b;
    private String Question;
    private int correct;
    Random rand = new Random();
    Scanner input = new Scanner(System.in);
    int count = 0;

    Question(int c, int d) {
        x = rand.nextInt(20);
        y = rand.nextInt(20);
    }

    public void askQuestion() {
        if (a > b) {
            System.out.println("What is " + a + " - " + b + " ?\n");
            correct = a - b;
        } else {
            System.out.println("What is " + a + " + " + b + " ?\n");
            correct = a + b;
        }
    }

    public void Check() {
        int response = Integer.parseInt(input.next());
        if (response == correct) {
            System.out.printf("yes.\n");
            count++;
        } else {
            System.out.printf("No. It is " + correct + ".\n");
        }
    }
}

我的主要方法是这样的

public class Main {
    public static void main(String[] args) {
        Question q1 = new Question(1,2);
        for (int i = 1; i < 10; i++) {
            q1.askQuestion();
            q1.check();
        }
    }
}

在我的输出中,它显示了带有两个随机数的问题,但它一遍又一遍地打印相同的问题。例如:

What is 13 - 1 ?

12
That is correct.
What is 13 - 1 ?

12
That is correct.
What is 13 - 1 ?

3
Wrong!. The answer is 12.
What is 13 - 1 ?

最终我希望我的输出看起来像:

What is 4 + 6?

What is 7 - 3?

任何帮助解决这个问题?让这个游戏更具互动性?欣赏它。

【问题讨论】:

  • xy 在您的 Question 类中定义在哪里?

标签: java arrays class object operator-keyword


【解决方案1】:

您的问题是由于您正在创建 一个 Question 对象,该对象会生成两个随机数(在您的情况下为 13 和 1)。然后,您将经历一个询问 10 个问题的循环,但您使用相同的 Question 对象——因此您每次都使用相同的随机数。要解决此问题,请进行以下更改:

在您的 Question 构造函数中,去掉参数,您不需要它们。赋值给变量ab

    private Question(){
        a = rand.nextInt(20);
        b = rand.nextInt(20);
    }

因此,每次创建问题时,您都会生成两个随机数,分配给您之前在顶部代码中声明的变量(在您的代码中,ab 已声明,但未使用)。

然后在你的 main 中,将其更改为以下内容:

public static void main(String[] args) {
    for(int i = 0; i < 10; i++) {
        Question q1 = new Question();
        q1.askQuestion();
        q1.check();
    }
    System.out.println("Number correct: " + count); //print amount correct, to use this make variable "count" static.
}

变化在于,现在您每次通过循环时都会创建一个新的 Question 对象,并获取新的随机值。每次它提出一个新问题时,它都会用新的随机值创建一个新的 Question 对象并覆盖旧的。在你给出并检查答案后,它会问问题 10 次,之后程序会输出正确答案的数量并停止。

3 个问题的示例输出:

What is 17 - 15 ?

2
yes.
What is 8 + 11 ?

19
yes.
What is 9 - 0 ?

5
No. It is 9.
Number correct: 2

【讨论】:

    【解决方案2】:

    如果您想要一种使用随机数和运算符动态询问问题的方法,您可以创建一个如下所示的Operator 枚举来处理计算左侧值和右侧值的结果。

    此外,对System.out.print 的调用应尽可能在主程序中。相反,您应该从Question 返回字符串。

    您需要做的就是将两个随机生成的数字传递给 Operator 枚举并要求它计算结果。

    考试(主要)

    package exam;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Exam {
        private static int correctCount = 0;
        private static List<Question> questions = randomQuestions(10);
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            questions.stream().forEach(question -> ask(question, input));
            input.close();
            stats();
        }
    
        private static void ask(Question question, Scanner input) {
            System.out.print(question.askQuestion());
            double guess = input.nextDouble();
            boolean isCorrect = question.makeGuess(guess);
            System.out.println(question.explain(isCorrect));
            System.out.println();
            correctCount += isCorrect ? 1 : 0;
        }
    
        private static void stats() {
            double percentage = (correctCount * 1.0d) / questions.size() * 100;
            System.out.printf("Correct: %.2f%% (%d/%d)%n", percentage, correctCount, questions.size());
        }
    
        private static List<Question> randomQuestions(int count) {
            List<Question> questions = new ArrayList<Question>();
            while (count --> 0) questions.add(new Question());
            return questions;
        }
    }
    

    问题(类)

    package exam;
    
    import java.util.Random;
    
    public class Question {
        private static final Random RAND = new Random(System.currentTimeMillis());
    
        private double left;
        private double right;
        private Operator operator;
    
        public Question(double left, double right, Operator operator) {
            this.left = left;
            this.right = right;
            this.operator = operator;
        }
    
        public Question(int max) {
            this(randInt(max), randInt(max), Operator.randomOperator());
        }
    
        public Question() {
            this(10); // Random 0 -> 10
        }
    
        public String askQuestion() {
            return String.format("What is %s? ", operator.expression(left, right));
        }
    
        public String explain(boolean correct) {
            return correct ? "Correct" : String.format("Incorrect, it is: %.2f", calculate());
        }
    
        public boolean makeGuess(double guess) {
            return compareDouble(guess, calculate(), 0.01);
        }
    
        private double calculate() {
            return operator.calculate(left, right);
        }
    
        @Override
        public String toString() {
            return String.format("%s = %.2f", operator.expression(left, right), calculate());
        }
    
        private static boolean compareDouble(double expected, double actual, double threshold) {
            return Math.abs(expected - actual) < threshold;
        }
    
        private static double randInt(int range) {
            return Math.floor(RAND.nextDouble() * range);
        }
    }
    

    运算符(枚举)

    package exam;
    
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    import java.util.Random;
    
    public enum Operator {
        ADD("+", (left, right) -> left + right),
        SUB("-", (left, right) -> left - right),
        MUL("*", (left, right) -> left * right),
        DIV("/", (left, right) -> left / right);
    
        private static final Random RAND = new Random(System.currentTimeMillis());
        private static final List<Operator> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
        private static final int SIZE = VALUES.size();
    
        public static Operator randomOperator() {
            return VALUES.get(RAND.nextInt(SIZE));
        }
    
        private String symbol;
        private Operation operation;
    
        private Operator(String symbol, Operation operation) {
            this.symbol = symbol;
            this.operation = operation;
        }
    
        public double calculate(double left, double right) {
            return operation.calculate(left, right);
        }
    
        public String expression(double left, double right) {
            return String.format("%.2f %s %.2f", left, symbol, right);
        }
    
        @Override
        public String toString() {
            return symbol;
        }
    }
    

    操作(接口)

    package exam;
    
    public interface Operation {
        double calculate(double left, double right); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2016-02-16
      相关资源
      最近更新 更多