如何确定.text文件中整数列表的最小值和最大值?

时间:2015-02-25 22:21:28

标签: java eclipse

我的目标是读取一个填充了未知数量的整数的.text文件,并找到总和/平均值/分钟/最大值。 我找到了总和和平均值,我只需要帮助从.text文件中找到min和max。这是我到目前为止所拥有的。

public static void main(String[] args)
{
    Scanner file = null; //initializes file to empty
    int cnt=0;
    int sum = 0;
    double average;
    try
    {
        //attempt to open file.
        file = new Scanner(new FileInputStream("pd06.txt"));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("File Not found. Error 404");
        System.exit(2);
    }

    while(file.hasNextInt())
    {

        sum+=file.nextInt();//sums all numbers within the file 
        cnt++;              // counts all numbers in file.      
                            // Used in average. 
    }
    average = (double)sum / cnt; //Average

    System.out.println("There are "+cnt+" numbers in "
            + "the file.");
    System.out.println("The sum of which is "+sum);
    System.out.printf("The average of all %d numbers "
            + "is %.2f\n",cnt ,average);
}

2 个答案:

答案 0 :(得分:2)

使用临时变量(一个用于最大值,一个用于最小值)。将从文件中获得的整数存储在变量中,并将其每次与max和min变量进行比较。每当找到新的最大值和最小值时,请更新这两个变量。

int number = 0;
int max = Integer.MIN_VALUE; //Give lowest 'int' number (-2147483648) if your file has -ve numbers also.
int min = Integer.MAX_VALUE; //Highest value for int
while(file.hasNext()) {
    number = file.nextInt();
    if(number > max) {
        max = number; //assuming you have all positive numbers in your file
    }
    if(number < min) {
        min = number;
    }
}

答案 1 :(得分:0)

您也可以仅在第一次设置minmax等于number并使用布尔值来执行此操作一次。

    int number = 0;
    int max = 0;
    int min = 0; 
    boolean firstTime = true;
    while(file.hasNext()) {
        number = file.nextInt();
        if(firstTime)
        {
            max = number;
            min = number;
            firstTime = false;
        }
        if(number > max) 
            max = number;

        if(number < min) 
            min = number;
    }