gpt4 book ai didi

java - 在Java中切换对象数组中的最小值和最大值

转载 作者:行者123 更新时间:2023-12-02 12:26:26 26 4
gpt4 key购买 nike

我被指示在 Java 中交换对象数组中的最大和最小值。我写了我的代码,看起来很合理,但由于某种原因,这些值没有切换???我不太确定我的代码有什么问题,有人可以指出我正确的方向吗?谢谢!!

这是我的代码:

public class Measurables
{
/**
Swaps the values with the smallest and largest measure.
@param objects an array of objects of a class that implements the
Measurable interface.
*/
public static void swapMinAndMax(Measurable[] objects)
{

Measurable largest = objects[0];
Measurable smallest = largest;
for (int i = 1 ; i < objects.length ; i++)
{
Measurable current = objects[i];
if ( largest.getMeasure() < current.getMeasure())
{
largest = current;
}
if (smallest.getMeasure() < current.getMeasure())
{
smallest = current;
}
Measurable temp = largest;
largest = smallest;
smallest = temp;

}
}
}

这是我运行测试程序时得到的结果:

Testers

Running Tester.java

fail
[Uruguay, Thailand, Belgium]
Expected: [Uruguay, Belgium, Thailand]
Running Tester2.java

fail
[BankAccount[balance=1000.0], BankAccount[balance=3000.0], BankAccount[balance=2000.0]]
Expected: [BankAccount[balance=3000.0], BankAccount[balance=1000.0], BankAccount[balance=2000.0]]
Running Tester3.java

pass
[Uruguay]
Expected: [Uruguay]

最佳答案

您应该存储元素的索引,以便在确定最小和最大索引后执行交换。另外,你似乎已经将比较换成了最小的。比如,

public static void swapMinAndMax(Measurable[] objects) {
int largest = 0, smallest = 0;
for (int i = 1; i < objects.length; i++) {
Measurable current = objects[i];
if (objects[largest].getMeasure() < current.getMeasure()) {
largest = i;
}
if (objects[smallest].getMeasure() > current.getMeasure()) {
smallest = i;
}
}
// Now swap, we know the indexes.
Measurable temp = objects[largest];
objects[largest] = objects[smallest];
objects[smallest] = temp;
}

关于java - 在Java中切换对象数组中的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45449720/

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