我的作业要求我做一个数学游戏,在该数学游戏中,我提示用户回答数学问题,然后向他们显示答案。我已经创建了MathGame类,但是当我创建MathGame的实例时,它要求我放入两个整数,我不知道这两个整数是因为我试图随机生成它们。

问题:如何从类中获取随机数以传递到MathGame实例?

下面是MathGame

在下面,我试图弄清楚MathGame实例的主要含义。

import java.util.Random;

public class MathGame {

    private int operand1;
    private int operand2;
    private int solution;

    public MathGame(int operand1, int operand2) {
        this.operand1 = operand1;
        this.operand2 = operand2;
    }

    public int genRandom1() {
        Random rand = new Random();
        int randNum = rand.nextInt(0) + 20;
        randNum = operand1;
        return operand1;
    }

    public int genRandom2() {
        Random rand = new Random();
        int randNum2 = rand.nextInt(0) + 20;
        randNum2 = operand2;
        return operand2;
    }

    public int getoperand1() {
        return operand1;
    }

    public int getoperand2() {
        return operand2;
    }

    public String question() {
        return "What is" + operand1 + operand2 + "?";
    }

    public String solution() {
        int solution = operand1 + operand2;
        return "The correct answer is: " + solution;
    }

}


我在MathGame实例中遇到错误,因为我需要经历两个整数,但是我显然不知道这些整数,因为它们应该是随机生成的,这是我在课堂上所做的。

import java.util.Scanner;

public class MathGameMain {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        MathGame game1 = new MathGame();
    }

}

最佳答案

您可能想要更改为以下内容:

import java.util.Random;


public class MathGame {

  private int operand1;
  private int operand2;
  private int solution;

  public MathGame ()
  {
    this.operand1 = getRandom();
    this.operand2 = getRandom();
  }

  public int getRandom()
  {
    Random rand = new Random();
    int randNum = rand.nextInt(20);
    return randNum;
  }

  public int getoperand1()
  {
    return operand1;
  }

  public int getoperand2()
  {
    return operand2;
  }

  public String question()
  {
    return "What is" + operand1 + " + " + operand2 + "?";
  }

  public String solution()
  {
    int solution = operand1 + operand2;
    return "The correct answer is: " + solution;
  }

}


初始化MathGame时,应生成随机数。如果您要随机生成数字,则无需传递数字。

10-08 04:15