gpt4 book ai didi

java - 将随机数传递到对象的实例中

转载 作者:行者123 更新时间:2023-11-30 03:41:52 25 4
gpt4 key购买 nike

我的作业要求我做一个数学游戏,在游戏中我提示用户回答数学问题,然后向他们展示答案。我已经创建了 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 初始化时生成随机数。如果您要随机生成数字,则无需传递数字。

关于java - 将随机数传递到对象的实例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26680530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com