简体   繁体   中英

Adding integers of array upto some number (java)

I have a java question.

I have two int[] arrays: cdn and cmn .
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}
cmn is {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. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. 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} . 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. Note that my program starts to loop from the beginning of cdn over and over again, because 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

and you also need to put plus = 0 into the loop

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 you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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