gpt4 book ai didi

java - 在数组中生成随机数,将它们相加并将答案存储在数组中

转载 作者:行者123 更新时间:2023-12-02 08:12:40 29 4
gpt4 key购买 nike

我是 Java 新手,正在尝试解决以下问题

这就是我的故事:程序生成 20 到 100 个数字,并将每个数字存储在数组中。生成后,程序必须将两个数字相加并将答案存储在数组中。示例

randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]

等等..

完成后,我会检查用户输入的答案并计算正确答案。

问题是:我不知道如何将两个数字相加并将其存储在数组中。这看起来很容易,但我的经验还不够:)

目前我被困在这里,如果有人可以解释或帮助我如何解决这个问题,我将非常感激。

public class gNumber {
private final int[] num = new int[20]; // array of randomly generated numbers
private int[] answers; // array of correct answers and UserAnswers
private final int[] userAnswers = new int[10];
private int numOfCorrect = 0;

// Accessor to get the randomly generated number
int getNumbers(final int n) {
return num[n];
}

int numOfCorrectAnswers() {
return numOfCorrect;
}

// Mutator to store store user input
void setUsrAnswers(final int _index, final int answer) {
userAnswers[_index] = answer;
}

// Method to generate random 20 numbers
public void RandomN() {

for (int i = 0; i < num.length; i++) {
final int randomNum = (int) (Math.random() * 100);
num[i] = randomNum;
final int a = num[i];
// int b =num[i];
answers[i] = a + a;
System.out.println(i + ")" + num[i] + answers[i]);
}

}

// method to add two numbers and store in in answers array
public void add(int arg1, int arg2) {
int b = 0;
while (b < 10) {
arg1 = num[b];
arg2 = num[b + 1];
answers[b] = arg1 + arg2;

System.out.println(answers[b]);
b = b + 1;
}
}

// method to check user answers
public void usrInput(final int usrAnwer) {
for (final int num : answers) {
if (num == usrAnwer) {
numOfCorrect++;
}
}

}
}

最佳答案

一个非常简单的解决方案:

int N = 20; //20 Random numbers
int[] randomNumber = new int[N];
int[] answer = new int[N/2];

//Generate random numbers of size N
for (int i = 0; i < N; i++) {
randomNumber = generateRandom(0, 100);
}

//populate answers
for (int i = 0; i < answer.length; i++) {
answer[i] = randomNumber[i*2] + randomNumber[i*2 + 1];
}

//Generate a random number from [min, max]
private int generateRandom(int min, int max) {
return min + (int)(Math.random() * ((max - min) + 1));
}

解释在评论里。 :-)

关于java - 在数组中生成随机数,将它们相加并将答案存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109226/

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