3

I am trying to get the sum, average, max and min value from user input in array. sum, average and max is giving the correct output. But min value is not working. Where am I doing wrong would someone help me please to find out?

import java.util.Scanner;

public class minMaxSumAverage {
    public static void main(String args[]) {
        int n, sum = 0, max, min;
        double average = 0;

        Scanner s = new Scanner(System.in);
        System.out.println("Enter elements you want to input in array: ");
        n = s.nextInt();
        int a[] = new int[n];
        max = a[0];
        min = a[0];
        System.out.println("Enter all the elements:");
        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
            sum += a[i];
            average = (double) sum/a.length;
            if (a[i] > max) {
                max = a[i];
            }
            if (a[i] < min) {
                min = a[i];
            }
        }
        System.out.println("Sum is: " + sum);
        System.out.println("Average is: " + average);
        System.out.println("Max is: " + max);
        System.out.println("Min is: " + min);
    }
}

Output:

Enter elements you want to input in array: 
5
Enter all the elements:
25
5
10
6
4
Sum is: 50
Average is: 10.0
Max is: 25
Min is: 0

Min value should be 4.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82
  • 5
    When you create a primitive array, such as with `int a[] = new int[n];`, all of the elements are set to the given primitive's default value. So that line of code creates an int array of size n, where all elements are set to zero. When you do `min = a[0];` immediately after that, you're initializing min to 0, so you'll always get zero as your min (unless the input negative numbers). One easy way to fix this is to initialize min like this: `min = Integer.MAX_VALUE;` . That way, every number that you enter afterward is guaranteed to be no larger than `min`. – Jordan Jul 10 '19 at 18:50

6 Answers6

1

From Java-8 you can use streams to get this done in single line:

int[] a = new int[] { 20,11,2,3,4,7,8,90 };
int min = Arrays.stream(a).min().getAsInt();

for getting the maximum element, just replace the .min() with .max()


for getting sum: Arrays.stream(a).mapToInt(Integer::intValue).sum();

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
1

I have updated you code. Please check following code to get min value from all element list.

Input :

Enter elements you want to input in array:

5

Enter all the elements:

25

5

10

6

4

Output :

Sum is: 50

Average is: 10.0

Max is: 25

Min is: 4

        Scanner scan = null;
        try {
            int n, sum = 0, max, min;
            double average = 0;
            scan = new Scanner(System.in);
            System.out.println("Enter elements you want to input in array: ");
            n = scan.nextInt();
            int a[] = new int[n];
            max = a[0];
            System.out.println("Enter all the elements:");
            for (int i = 0; i < n; i++) {
                a[i] = scan.nextInt();
                sum += a[i];
                average = (double) sum/a.length;
                if (a[i] > max) {
                    max = a[i];
                }
                /**
                // from here remove logic for get min value.
                if (a[i] < min) {
                   min = a[i];
                }
                **/
            }
            min = a[0];
            for(int i=0;i<a.length;i++){
                if(a[i] < min){
                  min = a[i];
                }
              }
            System.out.println("Sum is: " + sum);
            System.out.println("Average is: " + average);
            System.out.println("Max is: " + max);
            System.out.println("Min is: " + min);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            scan.close();
        }

Vimal
  • 411
  • 6
  • 28
0

Because min is initialized with 0. And in your loop you just ask if your current number is smaller than 0.

Try again with assigning the first value of your array as min.

Then it should work.

0
 int a[] = new int[n];
 max = a[0];
 min = a[0];

You have created an empty array a. Both max and min are initialized to 0. This works fine for max, but gives you the result you are seeing for min, because there is nothing smaller in your created array than zero.

To fix this, add your line min = a[0]; into the for loop after you have filled up your array with values, e.g.

for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
            sum += a[i];
            average = (double) sum/a.length;
            min = a[0];
            //if-statements here

Then, min = a[0] will no longer be zero, but will be the first value of the filled up array.

vs97
  • 5,765
  • 3
  • 28
  • 41
  • There will be a problem as each time `min` is changed in `if` statement it will again become the first element of array in the next iteration of `for-loop`. – Zain Arshad Aug 16 '19 at 10:42
0

As an alternative, you may want to consider a Stream...

public static void main(String args[]) {
    Scanner s = new Scanner(System.in);
    System.out.println("Enter count elements you want to input in array: ");
    int n = s.nextInt();
    int a[] = new int[n];
    System.out.println("Enter all the elements:");
    for (int i = 0; i < n; i++) {
        a[i] = s.nextInt();
    }
    s.close();

    IntSummaryStatistics iss = Arrays.stream(a).summaryStatistics();

    System.out.println("Sum is: " + iss.getSum());
    System.out.println("Average is: " + iss.getSum()/iss.getCount());
    System.out.println("Max is: " + iss.getMax());
    System.out.println("Min is: " + iss.getMin());
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Jeff Stewart
  • 125
  • 5
0

Please refer below code for a min, max, sum, average functionality :

List<Integer> intList= Arrays.asList(70, 80, 10, 20, 40, 50);
    Integer ans=0;
    int sum1= intList.stream().reduce(ans, (x,y) -> x+y);

    System.out.println(sum1);

    int sum2= intList.stream().reduce(ans, Integer::sum);
    System.out.println(sum2);
    int max= intList.stream().max(Integer::compare).get();

    System.out.println(max);

    int min= intList.stream().min(Integer::compare).get();

    System.out.println(min);

    Double avg= intList.stream().collect(Collectors.averagingInt(x-> x));

    System.out.println(avg);