Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我的最大乘积算法有什么问题_Java_Arrays_While Loop - Fatal编程技术网

Java 我的最大乘积算法有什么问题

Java 我的最大乘积算法有什么问题,java,arrays,while-loop,Java,Arrays,While Loop,代码如下: public static int MaxProduct(int... a){ // the max possible product from an array int i = 0; int j = 0; int m = 0; int n = a.length; while (i<n){ j++; while(j<n ){ if (a[i]*a[j] > m){

代码如下:

public static int MaxProduct(int... a){  // the max possible product from an array
    int i = 0;
    int j = 0;
    int m = 0;
    int n = a.length;
    while (i<n){
        j++;
        while(j<n ){
            if (a[i]*a[j] > m){
                m = a[i]*a[j];
                j++;
            }
        }
        i++;
    }
    return m;
}


System.out.println(MaxProduct(1,2,3,4,5));
public static int MaxProduct(int…a){//数组中可能的最大乘积
int i=0;
int j=0;
int m=0;
int n=a.长度;

而(i你需要做两个改变。检查下面两个待办事项

public static int MaxProduct(int... a) {  // the max possible product from an array
    int i = 0;
    int j = 0;
    int m = 0;
    int n = a.length;
    while (i < n) {
        j = i + 1;  // TODO: 1
        while (j < n) {
            if (a[i] * a[j] > m) {
                m = a[i] * a[j];
            }
            j++; // TODO:2
        }
        i++;
    }
    return m;
}
public static int MaxProduct(int…a){//数组中可能的最大乘积
int i=0;
int j=0;
int m=0;
int n=a.长度;
而(im){
m=a[i]*a[j];
}
j++;//待办事项:2
}
i++;
}
返回m;
}

您需要进行两项更改。请检查以下两项待办事项

public static int MaxProduct(int... a) {  // the max possible product from an array
    int i = 0;
    int j = 0;
    int m = 0;
    int n = a.length;
    while (i < n) {
        j = i + 1;  // TODO: 1
        while (j < n) {
            if (a[i] * a[j] > m) {
                m = a[i] * a[j];
            }
            j++; // TODO:2
        }
        i++;
    }
    return m;
}
public static int MaxProduct(int…a){//数组中可能的最大乘积
int i=0;
int j=0;
int m=0;
int n=a.长度;
而(im){
m=a[i]*a[j];
}
j++;//待办事项:2
}
i++;
}
返回m;
}

您不会重置
i
。而是使用for循环。此外,您应该无条件地递增j。
然后我在调试器旁边看到arrayoutofbounds错误(这也是我所期望的)你不应该期望它。如果是这样的话,应该有一个MeChanistic到<代码> catch >代码>我应该为每个循环使用循环还是只使用内部/外部循环?也感谢你修复错误时,请考虑<代码> [i] *[j] < /代码>与<代码> a[j] *a[i]完全一样。
,因此无需同时处理这两个问题。您不必重置
i
。而是使用for循环。此外,您应该无条件地递增j。
然后我在旁边的调试器中看到arrayoutofbounds错误(这也是我所期望的)你不应该期望它。如果是这样的话,应该有一个MeChanistic到<代码> catch >代码>我应该为每个循环使用循环还是只使用内部/外部循环?也感谢你修复错误时,请考虑<代码> [i] *[j] < /代码>与<代码> a[j] *a[i]完全一样。
,因此无需同时处理这两个问题。