Java help: How to find largest number in scanned i

2019-10-04 19:13发布

问题:

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.

EDIT: I understand that largest/smallest are being compared to count. I now understand that mistake. I don't understand how to find the smallest/largest value that count encounters.

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

回答1:

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;

A quick summary of the changes made:

  1. Used a variable to get the next integer rather than calling nextInt each time the value is needed.
  2. Used said variable for comparison and summation.
  3. Moved the calculation for average out of the loop, since you only need the average for all n numbers in the file.

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?