将数组的整数添加到某个数字(java)

时间:2013-03-13 22:05:42

标签: java

我有一个java问题。

我有两个int[]数组:cdncmn cdn{1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} cmn{8,8,16} 我需要一个程序,它将cdn[]的连续整数加到cmn[init]并返回加法中使用的整数。然后它继续从cdn[]的下一个整数添加到cmn[init+1]并返回整数。对于上面的数组,这样做了3次:第一次返回值是7,第二次是7,第三次是16.整数的数量可以收集到int[],这是{7,7,16}。我的代码是:

int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
 for(int j = 0; j < cdn.length; j++){
    plus += cdn[j];
    numofints++;
  if(plus == cmn[init]){
   init++;
  }
 }
}
System.out.print(numofints);

其中m2的大小为cmn,在这种情况下为3。请注意,我的程序开始一遍又一遍地从cdn的开头循环,因为j = 0。我希望它从前一次结束的地方开始! 我希望你有一个解决方案。

比约

2 个答案:

答案 0 :(得分:2)

只需将j拉出外圈,然后使用while代替for进行内循环

您还需要将plus = 0放入循环

public class T {
  public static void main(String[] args) {
    int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
    int[] cmn = {8,8,16};

    int numofints = 0;
    int init = 0;
    int m2 = 3;

    int j = 0;
    while(init < m2){
     int plus = 0;
     while(j < cdn.length){
        plus += cdn[j];
        j++;
        numofints++;
        if(plus == cmn[init]){
          init++;
          System.out.println(j);
          break;
        } 
      }
    if (j == cdn.length) break;
    }
  }
}

答案 1 :(得分:0)

if(plus == cmn[init]){ if(plus >= cmn[init])不应该{{1}}?如果你完全改变了cdn并且“plus”碰巧超过了“cfn [init]”,那么你的代码就会崩溃。