Java 方法查找最高价格



我的findmaxprice方法返回数组中具有最高价格的第一辆车的索引。如果未找到,则返回 -1。

据我所知,return会停止 for 循环。 关于如何在保持循环搜索最高价格的同时避免它的任何建议?

public int findmaxprice() {
double max =0;
for(int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
return i; //the problem is here
}   
}
return -1;
}

你几乎回答了自己 - 只是不要在 for 循环中返回。

public int findmaxprice() {
double max =0;
int maxIndex = -1;
for( int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
maxIndex = i;
}   
}
return maxIndex;
}

将 return 语句移到循环之外


findmaxprice method: returns the index of the first Car in the array with the maximum price. If it is not found, -1 is returned. as far as i know, return will stop the for loop , any advice on how to avoid it while keep the loop search for max price ?
public int findmaxprice() {
double max =0;
for( int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
}   
}
if(max != 0){
return max;
} else {
return -1;
}
}

以下方法将解决您的问题。此外,它还使您能够指定最低价格,高于该价格将考虑汽车价格进行最大计算。如果不需要这样的边界,则可以像findMaxPrice(0)一样在函数调用中保留此 0。

public int findMaxPrice(int min) {
double max = min;
int maxPriceCarIndex = -1;
for (int i = 0; i < nCars; i++) {
if (max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
maxPriceCarIndex = i; //reassign the index here
}
}
return maxPriceCarIndex;
}

也许你只需要"最贵"的汽车,而不是汽车的索引,那么你可以考虑使用流

import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
public class Test {
public static void main(String[] args) {
new Test().testGetMostExpensiveCar();
}
private void testGetMostExpensiveCar() {
// test null array
Car[] cars = null;
Car mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive); // prints null
// test empty array
cars = new Car[10];
mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive); // prints null
//test array with cars
cars[0] = new Car(10.0);
cars[5] = new Car(20.0);
cars[8] = new Car(30.0);
cars[8] = new Car(30.0);
mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive);// prints Car [price=30.0]
}
/**
* @param cars
* @return the most Expensive car, null if the array is empty or no car is in
*         the array
*/
public Car getMostExpensiveCar(Car[] cars) {
if (cars == null) {
return null;
}
return Arrays.stream(cars) // creates a Stream<Car> (take a look at e.g. https://www.baeldung.com/java-8-streams)
.filter(Objects::nonNull) // because there can be "null" values in the array
.max(Comparator.comparing(Car::getPrice)) // compares the car by price asc
.orElse(null); // return null if no element is found
}
private class Car {
private double price;
public Car(double price) {
super();
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [price=" + price + "]";
}
}
}

最新更新