简体   繁体   English

Java如何将数组的元素与同一数组的所有其他元素进行比较

[英]Java how to compare an element of an array with all the other elements of the same array

Let's suppose we have an array of integer elements x[N]. 假设我们有一个整数元素x [N]的数组。 How can I do to know if the element x[1] for example is greater than or equal to all the others elements of the same array? 我怎么知道例如元素x [1]是否大于或等于同一数组的所有其他元素? I used the for-loop, but it doesn't work because I want to check if an element is greater than all the others to do something. 我使用了for循环,但是它不起作用,因为我想检查某个元素是否大于所有其他元素才能执行某项操作。 If I use for-loop, instead, if the element is greater than one of the others elements, it does something, and this is wrong for my purposes. 如果我使用for循环,则如果该元素大于其他元素之一,则它会执行某些操作,这对我而言是错误的。 Can you help me please? 你能帮我吗?

Here an example of what I mean: 这是我的意思的示例:

for(int i = 0; i < num && i!= j; i++) {
    if(elementiInseriti[j] >= elementiInseriti[i]) {
         do something; 
    }
}

You can do 你可以做

int x = 1; //position you wanna compare
boolean state = true;
for(int i = 0; i < elementiInseriti.length; i++) {
    if(elementiInseriti[x] < elementiInseriti[i]) {
        state = false;
        break; //no need to check for other elements coz at least 1 lesser than the conpared
    }
}
if(state)
    // do your stuffs

Use a boolean variable 使用布尔变量

        boolean doSomething = true;
        for(int i = 0; i < num && doSomething; i++) {
            if(elementiInseriti[j] < elementiInseriti[i]) {  
               doSomething = false;
            }
        }
        if (doSomething)
            // do something

If elementiInseriti[j] is smaller than any of the other elements, the flag would be false, and you won't do something. 如果elementiInseriti[j]小于任何其他元素,则该标志将为false,并且您将不会做任何事情。

The basic idea is that you need to go over the entire array and accumulate a boolean as long as the the given element is the greatest. 基本思想是,只要给定元素最大,就需要遍历整个数组并累积一个boolean Note that you cannot have the i!=j condition in the for loop as this will terminate the loop prematurely and only check the elements against the elements before it in the array: 请注意,您不能for循环中使用i!=j条件,因为这会过早地终止循环,并且只能根据数组中之前的元素检查元素:

boolean isGreatest = true;
for(int i = 0; i < elementiInseriti.length && isGreatest; i++) {
    if (i != j && elementiInseriti[j] < elementiInseriti[i]) {
         isGreatest = false;
    }
}

if (isGreatest) {
    // do something;
}

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

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