首页 > 解决方案 > 如何在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]);
    }
}

标签: javaarrays

解决方案


也定义minindex外部。此外,您必须同时更新 (minminindex)

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]);

推荐阅读