Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

input - Java help: How to find largest number in scanned in file?

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...