Java生成随机数组值

Java生成随机数组值,java,arrays,Java,Arrays,我有一个简单的事实Java项目,它生成随机事实。 单击“随机”按钮时,我希望显示一个随机事实,并查找该事实编号 String factNumber[] = { "Fact 1", "Fact 2", "Fact 3", "Fact 4", "Fact 5", }; public String randomButtonNumber() { return

我有一个简单的事实Java项目,它生成随机事实。 单击“随机”按钮时,我希望显示一个随机事实,并查找该事实编号

String factNumber[] = {
            "Fact 1",
            "Fact 2",
            "Fact 3",
            "Fact 4",
            "Fact 5",
};

public String randomButtonNumber() {
            return factNumber[i];
        }

String facts[] = {"Elephants are the only mammals that can't jump.",
            "Candles will burn longer and drip less if they are placed in the freezer a few hours before using.",
            "Potatoes have more chromosomes than humans.",
            "You burn more calories sleeping than you do watching television.",
            "Animals that lay eggs don't have belly buttons.",
};

public String randomButton() {
        Random random = new Random();
        i = random.nextInt(facts.length);
        return facts[random.nextInt(facts.length)];
    }
现在,我的代码生成了一个随机事实,但事实数字保持在1。

试试这个:

public String randomButton() {
    Random random = new Random();
    i = random.nextInt(facts.length);
    return facts[i];
}

您正在生成两个不同的数字。只需使用
i

 i = random.nextInt(facts.length);
 return facts[i];

这会解决你的问题。每次你打一个random.next(facts.length)电话,就会得到两个随机数,而且它们相同的概率更小

public String randomButton() {
    Random random = new Random();
    return facts[random.nextInt(facts.length)];
}

可能
返回事实[i]?您调用了两次
Random.nextInt()
。一次去商店,一次又一次去了解事实。你应该只给这个打一次电话。完全一样
// Remember, facts.length returns how many elements in the array
// and new Random.nextInt() will generate a new result on every call

// These are your facts:

String facts[] = {
    "Elephants are the only mammals that can't jump.",
    "Candles will burn longer and drip less if they are placed in the freezer a few hours before using.",
    "Potatoes have more chromosomes than humans.",
    "You burn more calories sleeping than you do watching television.",
    "Animals that lay eggs don't have belly buttons.",
};


// Here you get a random fact
public String getRandomFactWithNumber() {
    // Generate a random number between 0 and facts.length
    int factNumber = new Random.nextInt(facts.length);

    // Return the fact with its number
    return "Fact " + factNumber + ": " + facts[factNumber];
}

// And if you only want a fact, without the number
public String getRandomFact() {
    // Generate a random number between 0 and facts.length
    int factNumber = new Random.nextInt(facts.length);

    // Return the fact
    return facts[factNumber];
}