Question

Thanks in advance. I'm having trouble figuring out why my code is giving me trouble when I print a minimum value for this array. It seems to be retaining the initial 0 value for min, but I'm not sure how to correct this. Max works fine. Did I set the max and min values in the wrong part of the program?

Also, this is my first assignment with arrays so I might have some questions about printing subscripts later on.

Thanks again!

EDIT- this fixed the problem, to my knowledge. Thanks Dan W.

 for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
        System.out.print("Enter a new number. This will continue until "
                + "you reach the size of the array. ");
        arrayOfNumbers[i] = keyboard.nextInt();
    }
            int max = arrayOfNumbers[0];
            int min = arrayOfNumbers[0];

package program8;

import java.util.Scanner;

public class arrayPrint {

    public static void main(String[] args) {
        final int NUMBER_OF_ELEMENTS;
      Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the amount of numbers the array will read in. ");
        NUMBER_OF_ELEMENTS = keyboard.nextInt();
                int arrayOfNumbers[] = new int[NUMBER_OF_ELEMENTS];
                int max = arrayOfNumbers[0];
                int min = arrayOfNumbers[0];
        for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
            System.out.print("Enter a new number. This will continue until "
                    + "you reach the size of the array. ");
            arrayOfNumbers[i] = keyboard.nextInt();
        }
        for (int i = 0; i < arrayOfNumbers.length; i++) {
            if (max <= arrayOfNumbers[i])
                max = arrayOfNumbers[i];
        }
        for (int i = 0; i < arrayOfNumbers.length; i++) {
            if (min >= arrayOfNumbers[i])
                min = arrayOfNumbers[i];
        }
                System.out.print(+max+ "max and " +min+ " min");
        }


}
Was it helpful?

Solution

What values are you inputting? Because an int has a default value of 0: here So, if you're only inputting positive numbers, the min will always be 0.

To avoid this, initialize min and max after you have the user input the numbers, that way the max and min are not defaulted to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top