Java – find the smallest integer based on the input

I have a task to find the minimum, maximum and average number of user input Basically, they enter positive integers, separated by spaces, and Java scrolls them and adds them I can find the sum, the average and the largest integer, but I can't find the smallest integer I think the best way to solve this problem is to set the variable representing the minimum int equal to the variable representing the maximum int outside the loop Then, in the loop, do the following:

if(getInt < min)
        {
            min = getInt;
        }

Where getInt is the value entered by the user and min is the minimum integer value But every time I run it, min returns 0

This is my complete code:

import java.util.Scanner;

public class exc5
{
    public static void main (String[] args)
    {  
        System.out.println("Write a list of nonnegative integers,each seperated by a space. To signal the end of the list,write a negative integer. The negative integer will not be counted");
        Scanner keyboard = new Scanner (system.in);
        keyboard.useDelimiter(" |\n");

        int count = 0;
        int sum = 0;
        int max = 0;
        int min = max;
        double average = 0;

        boolean notNull = true;

        while(notNull == true)
        {
            int getInt = keyboard.nextInt();

            if(getInt < 0)
            {
                notNull = false;
            }  
            else
            {          
                if(getInt > max)
                {
                    max = getInt;
                }

                if(getInt < min)
                {
                    min = getInt;
                }

                sum += getInt;
                count++;
                average = (sum)/(count);
            }
        }

        System.out.println("Sum = " + sum);
        System.out.println("Average = " + average);
        System.out.println("Max = " + max);
        System.out.println("Minimum = " + min);
    }

}

Any help is appreciated!

Solution

This:

int max = 0;
        int min = max;

Initialize min to zero (after all, Max has not yet become the largest integer.) So this:

if(getInt < min)

It will never be true Try to change this:

int min = max;

In this regard:

int min = Integer.MAX_VALUE; // largest possible Java `int`
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>