我是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/

10-11 20:13