HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Min and Max initialization

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mininitializationandmax

Problem

Is it a good practice to initialize the max to -100000 and min to 100000? Is there any other way to initialize both min and max to 0?

import javax.swing.*;
    import java.util.*;

public class arrayTajba
{
    public static void main(String[] args) throws Exception
    {
        String userStringInput = " ";
        String display = " ";
        int max = -100000;
        int min = 100000;
        int total = 0;
        double average;
        int i = 0;
        int [] num = new int [5];

        for (i = 0; i  max)
            {
                max = num[i];
            }
        }
            average = total / num.length;

        JOptionPane.showMessageDialog(null,"The numbers you have entered are:\n" + display + "\nSum of all numbers is: " + total + "\nAverage is: " + average + "\nMinimum number is: " + min + "\nMaximum number is: " + max,"Output Table" ,JOptionPane.INFORMATION_MESSAGE);
        }
    }i

Solution

Java has a couple of constants available that are commonly used in situations like this:

int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;


Using these two values ensures you cover the possible spectrum of valid input values.

In addition, a sadistic user would enter 5 large values, and cause your total value to overflow, creating a bad result. You should declare your total as a long value:

long total = 0;


That will prevent overflow (unless you have 2 billion input values.... ;-)

Finally, the last statement is a problem, it does integer division:

average = total / num.length;


It should convert one of the values to a double, so that floating-point division happens instead:

average = total / (double)num.length;

Code Snippets

int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
long total = 0;
average = total / num.length;
average = total / (double)num.length;

Context

StackExchange Code Review Q#55035, answer score: 12

Revisions (0)

No revisions yet.