简体   繁体   English

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

[英]Adding integers of array upto some number (java)

I have a java question. 我有一个java问题。

I have two int[] arrays: cdn and cmn . 我有两个int[]数组: cdncmn
cdn is {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} 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 is {8,8,16} cmn{8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. 我需要一个程序,它将cdn[]的连续整数添加到cmn[init]并返回添加中使用的整数。 Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. 然后它继续从cdn[]的下一个整数添加到cmn[init+1]并返回整数。 For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16} . 对于上面的数组,这样做了3次:第一次返回值是7,第二次是7,第三次是16.可以收集整数的数量和int[] ,即{7,7,16} The code I have is: 我的代码是:

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);

in which m2 is the size of cmn , which is 3 in this case. 其中m2cmn的大小,在这种情况下是3。 Note that my program starts to loop from the beginning of cdn over and over again, because j = 0 . 请注意,我的程序开始从cdn的开头cdn遍地循环,因为j = 0 I want it to start where it ended the previous time! 我希望它从前一次结束的地方开始! I hope you have a solution for me. 我希望你有一个解决方案。

Bjorn 比约恩

just pull j out of the outer loop, and use a while , instead of for , for the inner loop 只需将j拉出外循环,并使用一段while不是for ,用于内循环

and you also need to put plus = 0 into the loop 你还需要在循环中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;
    }
  }
}

Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init]) ? if(plus == cmn[init]){if(plus >= cmn[init])不要? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break. 如果你完全改变cdn并且“plus”碰巧超过“cmn [init]”,你的代码就会破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM