Java 检查数组中的每个元素是否具有相同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24709426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if every elements in array is of same value
提问by user3790782
Basically what I want to do is to check on each element in an array of int, if all elements are of the same value.
基本上我想要做的是检查 int 数组中的每个元素,如果所有元素都具有相同的值。
I create int array as below to pass to the method for comparing each array element, it return boolean true even tough the elements are not all the same values.
我创建如下 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
I suppose the method above will loop for and keep compare for each element of the array.
我想上面的方法将循环并保持对数组的每个元素进行比较。
When I print out the output, it showed that it only loop once, the return the boolean as true.
当我打印输出时,它显示它只循环一次,将布尔值返回为真。
I really lost the clue what could be wrong in my code.
我真的不知道我的代码可能有什么问题。
Perhaps I just overlook of some silly mistakes.
也许我只是忽略了一些愚蠢的错误。
采纳答案by J0e3gan
You only need one loop and should return false
as quickly as possible where applicable (i.e. when you encounter an element that doesn't match the first).
您只需要一个循环,并且应该false
在适用的情况下尽快返回(即当您遇到与第一个不匹配的元素时)。
You also need to account for the edge cases that the input array is null
or has one element.
您还需要考虑输入数组是null
或具有一个元素的边缘情况。
Try something like this, which I minimally adapted from the code you provided...
尝试这样的事情,我从您提供的代码中最低限度地改编...
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!");
}
}
...and outputs:
...和输出:
{3,3,4,3}: Nope!
{2,2}: Yup!
{2}: Yup!
null: Yup!
回答by dom
If all elements are the same value, why not use only one for loop to test the next value in the array? If it is not, return false.
如果所有元素都是相同的值,为什么不只使用一个 for 循环来测试数组中的下一个值?如果不是,则返回 false。
回答by Jobs
Right now, you are not checking if "all the elements are of the same value". You are ending the function and returning true whenever (the first time) two elements are equal to each other. Why not set the boolean value to true and return false whenever you have two elements that are not equal to each other? That way you can keep most of what you have already.
现在,您没有检查“所有元素是否具有相同的值”。每当(第一次)两个元素彼此相等时,您将结束该函数并返回 true。当您有两个不相等的元素时,为什么不将布尔值设置为 true 并返回 false 呢?这样你就可以保留大部分已经拥有的东西。
if(input[i+1]!=compare) return false;
if(input[i+1]!=compare) return false;
回答by Rhendz
public class Answer {
public static void main(String[] args)
{
boolean compare = false;
int count = 0;
int[] denominator = { 3, 3, 4, 3 };
for (int i = 0; i < denominator.length; i++)
{
if(denominator[0] != denominator[i])
{
count++;
}
}
if(count > 0)
{
compare = false;
} else
{
compare = true;
}
System.out.println(compare);
}
}
One mistake that I noticed right of the bat was that you declared your array as Int[], which is not a java keyword it is in fact int[]. This code checks your array and returns false if the array possesses values that are not equal to each other. If the array possesses values that are equal to each other the program returns true.
我注意到的一个错误是你将数组声明为 Int[],这不是一个 java 关键字,它实际上是 int[]。此代码检查您的数组,如果数组具有彼此不相等的值,则返回 false。如果数组具有彼此相等的值,则程序返回 true。
回答by Codejunky
If an array elements are equal you only need to compare the first element with the rest so a better solution to your problem is the following:
如果数组元素相等,则只需将第一个元素与其余元素进行比较,因此对您的问题的更好解决方案如下:
public static boolean bruteforce(int[] input) {
for(int i = 1; i < input.length; i++) {
if(input[0] != input[i]) return false;
}
return true;
}
You don't need more than one loop for this trivial algorithm. hope this helps.
对于这种微不足道的算法,您不需要超过一个循环。希望这可以帮助。
回答by gprathour
If you want to check if all elements are of same valuethen you can do it in a simpler way,
如果您想检查所有元素是否具有相同的值,那么您可以以更简单的方式进行,
int arr = {3,4,5,6};
int value = arr[0];
flag notEqual = false;
for(int i=1;i < arr.length; i++){
if(!arr[i] == value){
notEqual = true;
break;
}
}
if(notEqual){
System.out.println("All values not same");
}else{
System.out.println("All values same);
}
回答by Jae Heon Lee
If you're interested in testing array equality (as opposed to writing out this test yourself), then you can use Arrays.equals(theArray, theOtherArray)
.
如果您对测试数组相等性(而不是自己编写此测试)感兴趣,那么您可以使用Arrays.equals(theArray, theOtherArray)
.
回答by Rakesh KR
Try,
尝试,
Integer[] array = {12,12,12,12};
Set<Integer> set = new HashSet<Integer>(Arrays.asList(array));
System.out.println(set.size()==1?"Contents of Array are Same":"Contents of Array are NOT same");
Explanation:
解释:
Add the array to a set and check the size os set , if it is 1 the contents are same else not.
将数组添加到一个集合并检查大小 os set ,如果它是 1 内容相同,否则不。