我已经在Java中使用数组概念制作了该程序。尝试生成产品时,我以ArrayIndexOutOfBound的形式获取异常。

我使函数generateFNos(int max)生成给定数量的因子。例如,数字6将具有系数1,2,3,6。现在,我尝试将第一个数字和最后一个数字进行组合,以使乘积等于6。
我现在还没有使用在该数组中找到最小数字的逻辑。我待会再做。

问题是为什么我得到ArrayIndexOutOfBound异常? [我不知道]

下面是我的代码

public class SmallestNoProduct {

    public static void generateFNos(int max) {
        int ar[] = new int[max];
        int k = 0;
        for (int i = 1; i <= max; i++) {
            if (max % i == 0) {
                ar[k] = i;
                k++;
            }
        }
        smallestNoProduct(ar);
    }

    public static void smallestNoProduct(int x[]) {
        int j[] = new int[x.length];
        int p = x.length;
        for (int d = 0; d < p / 2;) {
            String t = x[d++] + "" + x[p--];
            int i = Integer.parseInt(t);
            j[d] = i;
        }
        for (int u = 0; u < j.length; u++) {
            System.out.println(j[u]);
        }
    }

    public static void main(String s[]) {
        generateFNos(6);
    }
}
****OutputShown****

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
    at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
    at SmallestNoProduct.main(SmallestNoProduct.java:52)


@编辑

改进的Code仅使用数组。

public class SmallestNoProduct {
    public static void generateFNos(int max) {
        int s = 0;
        int ar[] = new int[max];
        int k = 0;
        for (int i = 1; i <= max; i++) {
            if (max % i == 0) {
                ar[k] = i;
                k++;
                s++;
            }
        }
        for (int g = 0; g < s; g++) {
            System.out.println(ar[g]);
        }
        smallestNoProduct(ar, s);
    }

    public static void smallestNoProduct(int x[], int s) {
        int j[] = new int[x.length];

        int p = s - 1;
        for (int d = 0; d < p;) {
            String t = x[d++] + "" + x[p--];
            System.out.println(t);

            int i = Integer.parseInt(t);
            j[d] = i;
        }
        /*for (int u = 0; u < j.length; u++) {
            System.out.println(j[u]);
        }*/
    }

    public static void main(String s[]) {
        generateFNos(6);
    }
}

最佳答案

问题在于这条线

String t=x[d++]+""+x[p--];


x[p--]将尝试获取第7个位置值,因为p是数组x的长度,即6导致ArrayIndexOutOfBound异常。数组索引从0开始,因此最大位置是5而不是6。

您可以参考有关postfix表达式的this question

注意:我尚未检查您的逻辑,此答案仅是指出异常的原因。

关于java - 找到最小数K,如果存在,则其数字的乘积为N。例如:当N = 6时,最小数为k = 16(1 * 6 = 6)而不是k = 23(2 * 3 = 6),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30771754/

10-11 23:10
查看更多