简体   繁体   中英

add two Variables in one for loop java

Given 2 int arrays, each length 2, return a new array of length 4 containing all their elements. Ex:

plusTwo({1, 2}, {3, 4}) → {1, 2, 3, 4}

It is a sample question but I want do some extra practice. If the question did not specify the length of the two arrays. Then I wrote the code as :

public int[] plusTwo(int[] a, int[] b) {
  int[] c=new int[a.length+b.length];
  for(int i=0;i<a.length;i++){
      c[i]=a[i];
      for(int j=a.length;j<a.length+b.length;j++){
          for(int m=0;m<b.length;m++){
              c[j]=b[m];
          }
      }
  }
  return c;
}

My return is {1,2,4,4} I can not point out my mistake.:(

You need to write down what you want to archive and after that try to code this.

  • So first you need an array with size a+b (this is correct)
  • Now you want to copy everything from a into the beginning of c (your first loop this is correct)
  • Now you want to copy everything from b to c but beginning where you stopped copying from a (this is where you code becomes to complex with nested loops)

So your code should look like this:

int[] c= new int[a.length+b.length];
for(int i =0; i<a.length;i++) {
   c[i]=a[i];      
}

for(int i = 0; i<b.length;i++) {
   c[i+a.length]=b[i]; 
}

Or be fancy and use System.arraycopy which explains the steps needed a little bit better imho:

int[] c= new int[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length); //(copy a[0]-a[a.length-1] to c[0]-c[a.length-1]
System.arraycopy(b, 0, c, a.length, b.length); //copy b[0]-b[b.length-1] to c[a.length]-c[c.length-1]

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