繁体   English   中英

Array-1 CodingBat unlucky1 (java) 挑战

[英]Array-1 CodingBat unlucky1 (java) Challenge

我是一名计算机科学专业的高中生 class。对于家庭作业,我们必须为某些 CodingBat(实践编码网站)问题创建解决方案。 我遇到了这个问题的问题,其中一些问题包括数组的 OutOfBounds。 根据我的代码,我不太明白为什么会这样。 以下附加代码(下方)是我为 Array-1 (java) 中 unlucky1 的 CodingBat 问题创建的解决方案,它将挑战描述为:“我们会说 1 紧接着是 3 array 是一个“倒霉的”1。如果给定的数组在数组的前 2 个或最后 2 个位置包含倒霉的 a,则返回 true。

public boolean unlucky1(int[] nums) {
  int i = 0;
  for(i = 0; i < nums.length; i++)
    if(nums[i-1] == 1 && nums[i] == 3)
    {
      return true;
    }
    return false;
}

问题陈述是“如果给定数组在数组的前 2 个或后 2 个位置包含一个不幸的 a,则返回 true。”,因此您甚至不需要循环 - 您只需要检查前两个和后两个数组元素:

public boolean unlucky1(int[] nums) {
    return nums != null &&
           nums.length >= 2 &&
           (nums[0] == 1 && nums[1] == 3 ||
            nums[nums.length - 2] == 1 && nums[nums.length -1] == 3);
}

下面的代码是正确的方法。

0.public static boolean unlucky1(int[] nums){  //Firstly,declare the method 
                                               "static"
    1.  int length = nums.length;//Get the array length.
 
    2.if((nums[0] == 1 && nums[1] == 3) && ( nums[length - 2] == 1 && 
                                             nums[length] -1  == 3)){
    3.      return true;        
                } 
    4.  return false;       
                }

在第 2 行,您的代码是:“if(nums[i-1] == 1 && nums[i] == 3)”;

它显示 arrayoutofbound 因为起始数组索引为 0 并且您在 if 语句中贴标

" if(nums[0-1]...)which says if nums[-1] which is out of bounds."

还要检查数组的最后 2 个数字,您可以执行以下操作:

      ( nums[length - 1] == 1 && nums[length] == 3)) where : 

               " nums[length - 2] == 1" 
      checks 1 value before the last array value 
                         
                     and 
               " nums[length] - 1 == 3 "
             checks the last array value

暂无
暂无

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

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