这个将数组中的三个数字相加得到 30 的程序有什么问题

What's wrong with this program to add three numbers in an array to get 30

我想将三个小于 15 的奇数相加得到 30。

这是我的代码:

import java.util.*;

public class odd {
    public static void main(String args[]) {
        int n[]={1,3,5,7,9,11,13,15};
        int a,n1,n2,n3;
        Random rand=new Random();

    do {
        n1=n[(rand.nextInt(8)+1)];
        n2=n[(rand.nextInt(8)+1)];
        n3=n[(rand.nextInt(8)+1)];
        a=n1+n2+n3;}while(a!=30);
        System.out.println(n1);
        System.out.println(n2);
        System.out.println(n3);
    }
}

我遇到以下异常:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at oddno.odd.main(odd.java:12)

您的数组有 8 个元素,索引从 0 到 7。

因此改变

    n1=n[(rand.nextInt(8)+1)];
    n2=n[(rand.nextInt(8)+1)];
    n3=n[(rand.nextInt(8)+1)];

    n1=n[rand.nextInt(8)];
    n2=n[rand.nextInt(8)];
    n3=n[rand.nextInt(8)];

或按照 AxelH 的建议:

    n1=n[rand.nextInt(n.length)];
    n2=n[rand.nextInt(n.length)];
    n3=n[rand.nextInt(n.length)];

这里

int n[]={1,3,5,7,9,11,13,15}; // size of array is 8

虽然您获得了从 07 的索引。没有索引为 8.

的元素

这种方法很糟糕。对于初学者来说,如果总和无法达到,它将无限循环。设计算法至少与实现一样重要。考虑一些更聪明的方法:

  1. 您只能随机选择两个数字,从总数中减去它们并检查结果数字是否在集合中。这可能比随机抽取 3 个数字并计算总和要慢。简介一下。

  2. 如果你(系统地)尝试这三个数字的所有可能组合会稍微好一些。

  3. 继续,您可以建立一个类似 "tree" 的可能性结构并快速消除分支。例如,一旦抽到 1,就不能再抽 3、5 等等。通过这种方式,您可以逐步降低问题的维度,直到它变得非常微不足道。

至于你的实际错误,这是因为 Java 中的数组是从零开始的:n 范围从 n[0]n[7] 并包括 n[7]。如果您必须随机选择,则使用rand.nextInt(n.length)