基本上,我想做的是检查int数组中的每个元素,如果所有元素的值都相同。
我如下创建int数组,以传递给比较每个数组元素的方法,即使元素不是全部相同的值,它也会返回boolean true。
Int[] denominator = {3,3,4,3};
boolean compare;
compare = bruteforce(denominator);
public static boolean bruteforce(int[] input) {
int compare =0;
int count =0;
for (int i = 0; i < input.length; i++) {
compare = input[i];
while(count<input.length){
if(input[i+1]==compare){
return true;
}
i++;
count++;
}//end while
}//end for
return false;
}//end method
我想上面的方法将为数组的每个元素循环并保持比较。
当我打印输出时,它表明它仅循环一次,将布尔值返回为true。
我真的失去了线索,可能是我的代码出了什么问题。
也许我只是忽略了一些愚蠢的错误。
您只需要一个循环,并应false
在适用的情况下尽快返回(即,当遇到与第一个不匹配的元素时)。
您还需要考虑输入数组为null
一个元素或具有一个元素的极端情况。
尝试这样的事情,我至少根据您提供的代码进行了改编...
public class BruteForceTest {
public static boolean bruteforce(int[] input) {
// NOTE: Cover the edge cases that the input array is null or has one element.
if (input == null || input.length == 1)
return true; // NOTE: Returning true for null is debatable, but I leave that to you.
int compare = input[0]; // NOTE: Compare to the first element of the input array.
// NOTE: Check from the second element through the end of the input array.
for (int i = 1; i < input.length; i++) {
if (input[i] != compare)
return false;
}
return true;
}
public static void main(String[] args) {
int[] denominator = {3,3,4,3};
boolean compare = bruteforce(denominator);
// FORNOW: console output to see where the first check landed
System.out.print("{3,3,4,3}:\t");
if (compare)
System.out.println("Yup!");
else
System.out.println("Nope!");
// NOTE: a second array to check - that we expect to return true
int[] denominator2 = {2,2};
boolean compare2 = bruteforce(denominator2);
System.out.print("{2,2}:\t\t");
if (compare2)
System.out.println("Yup!");
else
System.out.println("Nope!");
/*
* NOTE: edge cases to account for as noted below
*/
// array with one element
int[] denominator3 = {2};
System.out.print("{2}:\t\t");
if (bruteforce(denominator3))
System.out.println("Yup!");
else
System.out.println("Nope!");
// null array
System.out.print("null:\t\t");
if (bruteforce(null))
System.out.println("Yup!");
else
System.out.println("Nope!");
}
}
...并输出:
{3,3,4,3}: Nope!
{2,2}: Yup!
{2}: Yup!
null: Yup!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句