【问题标题】:add two Variables in one for loop java在一个for循环java中添加两个变量
【发布时间】:2015-08-17 18:36:14
【问题描述】:

给定 2 个 int 数组,每个长度为 2,返回一个包含所有元素的长度为 4 的新数组。 例如:

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

这是一个示例问题,但我想做一些额外的练习。如果问题没有指定两个数组的长度。然后我把代码写成:

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

我的回报是 {1,2,4,4} 我不能指出我的错误。:(

【问题讨论】:

  • 你试过调试你的代码吗?
  • 导致此行为的错误是将三个 for 循环装箱成另一个。我不会解释为什么给定代码会导致这种行为,只是调试它。

标签: java arrays


【解决方案1】:

您需要写下您想要归档的内容,然后尝试编写此代码。

  • 所以首先你需要一个大小为 a+b 的数组(这是正确的)
  • 现在您想将所有内容从 a 复制到 c 的开头(您的第一个循环是正确的)
  • 现在您想将所有内容从 b 复制到 c,但从您停止从 a 复制的位置开始(这是您的代码因嵌套循环而变得复杂的地方)

所以你的代码应该是这样的:

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]; 
}

或者花哨并使用 System.arraycopy,它解释了所需的步骤,恕我直言:

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]

【讨论】:

  • 非常感谢。这对我很有帮助。
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 2018-02-23
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
相关资源
最近更新 更多