java - 如何在java中打印数组中的最小值?
问题描述
我有一个整数数组,我想使用 for 循环遍历它并找到最小值。我有一个最小值变量集,当程序在列表中移动时,它与当前索引进行比较,但是,它打印它遇到的每个索引,它小于变量最小值,而不是在末尾只打印一个程序。将System.out.println
语句放在 for 循环之外可以解决问题,但它不会让我这样做,因为它说有未定义的变量。
int Min = age[0];
for(int i = 0; i < age.length; i++) {
if (age[i] < Min) {
int minIndex = i;
System.out.println("Name of youngest athlete:" +
names[minIndex] + "\n age:" + age[minIndex] + "\n points:" +
points[minIndex]);
}
}
解决方案
也定义minindex
外部。此外,您必须同时更新 (min
和minindex
)
int min = age[0];
int minindex = 0;
for(int i = 1; i < age.length; i++) {
if (age[i] < min) {
minindex = i;
min = age[i];
}
}
System.out.println("Name of youngest athlete:" +
names[minindex] + "\n age:" + min + "\n points:" +
points[minindex]);
推荐阅读
- r - 在数据框中每第四列插入 8 个空 (NA) 列
- java - 将相同的数据添加到多个折线图
- django - 无法删除对象 - ?csrfmiddlewaretoken= 出现在 urlbar (django) 中当前 URL 的末尾
- sql - 列“column1”的类型与 UNPIVOT 列表中指定的其他列的类型冲突
- pandas - 如果列值存在于另一个数据框中,则从数据框中提取数据
- swift - 在 Swift [UI] 中使用 UserDefaults 变得疯狂
- android - Android - 从通知启动活动
- audio - 从电影中删除一个音轨会在复制时导致音频不同步,但在重新编码时不会 - 为什么?
- regex - 为什么这个正则表达式匹配这个字符串?
- ms-word - 如何在 Word 文档中设置药丸样式?