Java帮助,数组中的最小值

时间:2015-11-17 21:50:33

标签: java arrays

我正在尝试从我设置的数组中获取最小值,但它仍然返回0的值?!?!

import java.util.Scanner;
public class ACTScoring {

    /**
     * Stack Underflow
     * 11/17/15
     * ACT Scores are pretty neat
     */
    public static void main(String[] args) {
        int[] score = new int[12];
        Scanner inputTest = new Scanner(System.in);
        int totalScores = 0;
        double average = 0.0;
        int high = score[0];
        int low = score[0];

         for (int count = 0; count < score.length; count++){
             System.out.println("Please Enter in the score: ");
             score[count] = inputTest.nextInt();

         }
         for (int count = 0; count < score.length; count++){
             totalScores = totalScores + score[count];

             if(score[count]>high)
                 high=score[count];
             //low keeps outputting 0
             else if (score[count]<low)
                 low=score[count];

             average = (totalScores*1.0) / score.length;
         }


         System.out.println("Your average score is: " + average);
         System.out.println("Your Highest Score was: " +high);
         System.out.println("Your lowest Score was: "+ low);
    }

}

4 个答案:

答案 0 :(得分:1)

最好在进入循环之前将值初始化为它们所代表的值。

int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;

但更好的解决方案是在第一个循环中完成所有事情:

int length = 12;
for (int count = 0; count < length; count++){
     System.out.println("Please Enter in the score: ");
     int value = inputTest.nextInt();
     if (value < low) {
         low = value;
     }
     if (value > high) {
         high = value;
     }
     totalScores += value;
}
average = (totalScores * 1.0) / length;

答案 1 :(得分:0)

int high = score[0];
int low = score[0];

在这里,您将这些变量设置为新近初始化的数组在索引0处包含的内容。这是0。因此,只要您不输入负数,0将始终是您的结果。

如果你将这两行移到第一个for循环下面(数组实际填充的位置),那么你的代码应该可以工作。

答案 2 :(得分:0)

你正在初始化你的min和max 之前你在数组中有任何数据,所以两者都得0(int&#39; s默认值)。

这意味着如果所有输入都是正数,则min仍为零。

你需要将min和max的初始化移动到两个for循环之间

答案 3 :(得分:0)

获取数组中最低值的最简单方法之一是先将数组按升序排序,然后获取第一个值。

public static void main(String[] args){
    int[6] results;
    //initialize results
    Arrays.sort(results);
    System.out.println("Lowest: "+results[0]+". Highest: "+results[results.length-1]);
}

Look here for a good example