首页 > 解决方案 > 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;
}

标签: javaarraysmethods

解决方案


你几乎回答了自己 - 只是不要在 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;
}

推荐阅读