deathshot
deathshot

Reputation: 93

Java array minimum element within for-loop

OK, I have been at it for a long time now. I have looked after similar problems here in stack-overflow and I still can't make it work. I need to find the maximum values within an array and minimum values. Trying to find the minimum is the problem. I have literately tried everything from writing separate methods and so on and still the output in 0. Here is what I have tried:

import java.util.Scanner;

class ArrayMin {

  public static void main(String args[]) {
    @SuppressWarnings("resource")
    Scanner scanner = new Scanner(System.in);

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

    System.out.println("Enter elements of array :");
    for (int i = 0; i < 10; i++) {
      a[i] = scanner.nextInt();
      if (i == 9)
        break;
    }

    for (int i = 1; i < a.length; i++) {

      if (a[i] > max)
        max = a[i];

      else if (a[i] < min)
        min = a[i];

    }

    System.out.println("Result is max is :" + (max)); //if I input 1-10, output is 10
    System.out.println("Result is min is :" + (min)); //whatever number I input the output is always 0
  }
}

Upvotes: 0

Views: 3196

Answers (2)

Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Replace this.

   int max = Integer.MIN_VALUE;
   int min = Integer.MAX_VALUE;
...
    for (int i = 0; i < a.length; i++) {

      if (a[i] > max)
        max = a[i];

      if (a[i] < min)
        min = a[i];

    }
...

Upvotes: 1

rgettman
rgettman

Reputation: 178283

When you declare your array, it's initialized to all zeroes. Then you assign the min to your first element, which is zero. Presumably all values are >= to 0 once they're assigned, so the min is still zero, but the max is correct.

Establish your max and min after the for loop where you assign input values to the array.

for (int i = 0; i < 10; i++) {
  a[i] = scanner.nextInt();
  if (i == 9)
    break;
}
// Moved HERE.
int max = a[0];
int min = a[0];

Upvotes: 3

Related Questions