0

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
  }
}
4
  • 2
    Using a debugger to go through your code step by step should give you the answer quickly... Commented Jan 21, 2014 at 18:13
  • 2
    You initialize min to 0. So if you input numbers from [1-10] the min will always be 0. Also remove the if with the break in your for loop. Commented Jan 21, 2014 at 18:13
  • 1
    if (i==9) break; is redundant. If you take it out, i will be incremented to 10 and then the loop will exit because the i<10 condition is no longer true. Which is what you want. Commented Jan 21, 2014 at 18:34
  • @ajb Alright i will keep that in mind, good to know. The problem I was solving had a "sample starter" code written to begin with so I did not want to mess anything up. Commented Jan 21, 2014 at 18:42

2 Answers 2

3

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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];

    }
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.