0
import java.util.Scanner;

public class MaxMin {

    public static void main(String[] args) {

        Scanner myScanner = new Scanner(System.in);

        System.out.println("Please enter the arrays value : ");
        int userInput = myScanner.nextInt();

        int[] myArray = new int[userInput];

        System.out.println("please enter the values for arrays : ");

        int sum = 0;
        int max = myArray[0];
        int min = myArray[0];

        for (int i = 0; i < myArray.length; i++) {
            myArray[i] = myScanner.nextInt();
            sum = sum + myArray[i];
        }

        for (int i = 1; i < myArray.length; i++) {
            if (max < myArray[i]) {
                max = myArray[i];
            }

            if (min > myArray[i]) {
                min = myArray[i];
            }
        }

        System.out.println("The sum is : " + sum + " \nmax is : " + max + "\nmin is : " + min);
    }
}

OUTPUT------------------------------

Please enter the arrays value : 5 please enter the values for arrays : 5 63 23 58 6 The sum is : 155 max is : 63 min is : 0 // why 0

Geshode
  • 3,600
  • 6
  • 18
  • 32
  • Welcome to Stack Overflow! Please read [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions. –  Jan 26 '18 at 19:16
  • Your code is performing correctly. Given you input `"5 63 23 58 6"` the min of your *array* is `0`, because your array is size `5` (as entered), but you only input `4` elements, leaving the last element at with (default) value of `0`) – Bohemian Jan 26 '18 at 19:18
  • 1
    which would be immediately obvious with 2 seconds in the step debugger –  Jan 26 '18 at 19:19
  • You need to initialize `min` and `max` variables **after** you have inserted values in the array. Just move `int max = myArray[0]; int min = myArray[0];` after first for loop; – Yousaf Jan 26 '18 at 19:23

1 Answers1

1

You have assigned min and Max to myArray[0] before actually taking input of myArray values.

As myArray has default of zero min is assigned to zero.

Gaur93
  • 685
  • 7
  • 19