繁体   English   中英

卡在数组的for循环(java)中。 [i],[i + 1],[i + 2]

[英]Stuck with for loop (java) for arrays. [i], [i+1],[i+2]

因此,我在bat.com上编写代码,为期中的示例练习,并查看其中一个问题,我陷入了困境。 他们为什么在for循环条件语句中执行length-2。我不明白为什么我们必须减去2,也许这里有人可以快速解释它。 我知道这很简单,我没明白。 谢谢!

问题:

Given an array of ints, return true if .. 1, 2, 3, .. appears in the array somewhere. 

array123({1, 1, 2, 3, 1}) → true
array123({1, 1, 2, 4, 1}) → false
array123({1, 1, 2, 1, 2, 3}) → true`

解:

public boolean array123(int[] nums) {
  // Note: iterate < length-2, so can use i+1 and i+2 in the loop
  for (int i=0; i < (nums.length-2); i++) {
    if (nums[i]==1 && nums[i+1]==2 && nums[i+2]==3) return true;
  }
  return false;
}

为了不抛出IndexOutOfBound异常。 想象一下,如果没有-2并到达最后一个元素,并且在代码中尝试访问索引处的元素(最后一个+ 2),它将抛出异常,因为您想要到达的索引不是可用。

暂无
暂无

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

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