java - 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;
}
推荐阅读
- reactjs - react js中的道具是从父母到孩子还是从孩子到父母
- monit - 将 Monit 5.25.3 升级到 5.26 ...配置/安装
- mysql - 从同一个表中搜索逗号分隔的字符串
- acumatica - Acumatica:将快速流程添加到 Acumatica 应用程序?
- javascript - 具有延迟加载图像的 Puppeteer
- javascript - 如何使用没有 id 的 Javascript 访问元素?
- c# - PDFTRON 转换成功后不发布互操作进程
- python - 将 Keras 与 Ensemble Voting 分类器一起使用
- python - 不是 python 3 和 pandas 的 NaN 条件语句
- wolfram-mathematica - 以自定义格式打印 Solve 的输出