gpt4 book ai didi

java - 试图理解 3 个嵌套的 if 语句

转载 作者:行者123 更新时间:2023-12-01 16:59:10 25 4
gpt4 key购买 nike

假设我有一个由 5 个字符串组成的数组,与该数组相关的是 3 个大小相同的整数数组。例如`

String a[] = new String[5]
int x[] = new int[5]
int y[] = new int[5]

int z[] = new int[5]

因此 a[0],x[0],y[0],z[0] 都与同一事物相关。我想找出 x[] 中的哪个索引包含最高的数字。如果多个具有相同的最高数字,那么其中哪一个在 y[] 中具有最高数字,如果有多个具有相同的最高数字,则哪一个在 z[] 中具有最高数字(可以安全地假设z[] 中没有一个具有相同的最大值

我已尽力解释..

如果只检查前两个条件,这是最好的

for(int i=0;i<a.length;i++)
{

if(x[i]>=maximum){
if(x[i]==maximum)
{
if(y[i]>=maximum)
{
maximum=x[i];
winner=a[i];
maximum=y[i];
}
}
else
{
maximum=x[i];
winner=teams[i];
maximum=y[i];
}
}

这是我的新代码

static int compareValues(){
for (int i=0; i<a.length; i++){
int max =0;
int diff = x[i] - x[max];
if (diff == 0){
diff = y[i] - y[max];
}
if (diff == 0){
diff = z[i] - z[max];
}
if (diff > 0){
max = i
}
}
return max;

}

最佳答案

如果String[n]与每个n的int[n]相关,那么你真的应该正确地组合它们,使它们可比较 并对它们进行排序。

class Thing implements Comparable<Thing> {

final String a;
final int x;
final int y;
final int z;

public Thing(String a, int x, int y, int z) {
this.a = a;
this.x = x;
this.y = y;
this.z = z;

}

@Override
public int compareTo(Thing o) {
int diff = o.x - x;
if (diff == 0) {
diff = o.y - y;
}
if (diff == 0) {
diff = o.z - z;
}
return diff;
}

@Override
public String toString() {
return "{" + a + "," + x + "," + y + "," + z + "}";
}
}

public static int max(Thing[] things) {
// NB - This should really call compareTo.
int max = 0;
for (int i = 1; i < things.length; i++) {
int diff = things[i].x - things[max].x;
if (diff == 0) {
diff = things[i].y - things[max].y;
}
if (diff == 0) {
diff = things[i].z - things[max].z;
}
if (diff > 0) {
// Higher
max = i;
}
}
return max;
}

public void test() {
Thing[] things = new Thing[6];
things[0] = new Thing("Hello", 1, 2, 3);
things[1] = new Thing("There", 1, 2, 4);
things[2] = new Thing("Everyone", 0, 2, 3);
things[3] = new Thing("How", 9, 0, 3);
things[4] = new Thing("Are", 8, 9, 3);
things[5] = new Thing("You", 7, 2, 3);
System.out.println("Before: " + Arrays.toString(things));
System.out.println("Max: " + things[max(things)]);
Arrays.sort(things);
System.out.println("Sorted: " + Arrays.toString(things));
}

关于java - 试图理解 3 个嵌套的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com