[英]Array-1 CodingBat unlucky1 (java) Challenge
I'm a senior in high school taking a computer science class. For homework, we have to create solutions to certain CodingBat (practice coding website) problems.我是一名计算机科学专业的高中生 class。对于家庭作业,我们必须为某些 CodingBat(实践编码网站)问题创建解决方案。 I am experiencing problems with this question, some of which include OutOfBounds for the array.我遇到了这个问题的问题,其中一些问题包括数组的 OutOfBounds。 Based on my code, I can't quite figure out why this is happening.根据我的代码,我不太明白为什么会这样。 The following attached code (below) is what I have created as a solution to the CodingBat problem for unlucky1 in Array-1 (java), which describes the challenge as: “We'll say that a 1 immediately followed by a 3 in an array is an "unlucky" 1. Return true if the given array contains an unlucky a in the first 2 or last 2 positions in the array.以下附加代码(下方)是我为 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;
}
The problem statement is "Return true if the given array contains an unlucky a in the first 2 or last 2 positions in the array.", so you don't even need a loop - you just need to examine the first two and last two elements of the array:问题陈述是“如果给定数组在数组的前 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);
}
The following code is the correct method.下面的代码是正确的方法。
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;
}
In row 2,your code was: "if(nums[i-1] == 1 && nums[i] == 3)";在第 2 行,您的代码是:“if(nums[i-1] == 1 && nums[i] == 3)”;
It showed arrayoutofbound because the starting array index is 0 and you decalred in the if statement它显示 arrayoutofbound 因为起始数组索引为 0 并且您在 if 语句中贴标
" if(nums[0-1]...)which says if nums[-1] which is out of bounds."
Also to check the last 2 numbers of the array you do the following:还要检查数组的最后 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.