Java帮助:如何在文件中查找扫描的最大数字? [英] Java help: How to find largest number in scanned in file?

查看:174
本文介绍了Java帮助:如何在文件中查找扫描的最大数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到扫描文件数量的总和,数量,平均数,赔率数,最大值,最小值和平均值。除了最大/最小,我做了一切。
当程序运行时,最大/最小等于计数而不是产生计数遇到的最大/最小值。

I need to find the sum, count of, number of evens, number of odds, largest, smallest, and average of the numbers of the scanned file. I've done everything except largest/smallest. When the program runs, the largest/smallest equals the count instead of producing the largest/smallest value the count encounters.

编辑:我理解将最大/最小的数字与计数进行比较。我现在明白了这个错误。我不明白如何找到计数遇到的最小/最大值。

以下是我所做的:
注意: while循环之前的所有代码都是由我的教授预先编写的,并且代码不能以任何方式被篡改或更改。不允许使用数组。

Here is what I've done: NOTE: All code before while loop was prewritten by my professor and that code cannot be tampered with or altered in any way. Not allowed to use arrays either.

int count=0,sum=0, largest=Integer.MIN_VALUE,smallest=Integer.MAX_VALUE, evens=0, odds=0;
        double average=0.0;

        while (infile.hasNext())
        {
            count += 1;
            sum += infile.nextInt();
            average = sum/count;
            if (count > largest)
                largest = count;
            if (count < smallest)
                smallest = count;
            if (sum%2 != 0)
                odds++;
            else
                evens++;

        }
        infile.close();


推荐答案

您需要将正在阅读的值与之前的值进行比较最大值和最小值。因此,将您的值存储到变量中并将其用于比较/求和操作,如下所示:

You need to compare the values being read with the previous maximum and minimum values. So, store your values into a variable and use that for the comparison/summation operations, like so:

int current = 0;

while (infile.hasNext())
    {
        current = infile.nextInt();
        count += 1;
        sum += current;            
        if (current > largest);
            largest = current;
        if (current < smallest)
            smallest = current ;
        if (current%2 != 0)
            odds++;
        else
            evens++;

    }

    average = sum/count;

所做更改的快速摘要:


  1. 使用变量获取下一个整数,而不是每次需要值时调用 nextInt

  2. 使用所述变量进行比较和求和。

  3. 将计算平均移出循环,因为您只需要文件中所有n个数的平均值。

我仍然不知道你的意思是我不明白如何找到计数遇到的最小/最大值。什么 DOES 计算与它有什么关系?

I still have no idea what you mean by " I don't understand how to find the smallest/largest value that count encounters." What DOES count have to do with it at all?

这篇关于Java帮助:如何在文件中查找扫描的最大数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆