Home > Back-end >  Getting 0 for minimum value but the maximum value is okay
Getting 0 for minimum value but the maximum value is okay

Time:11-22

I am trying to input an array using a scanner. That part is already done. Now, I am tasked to get the maximum and minimum numbers from my input. I was able to get the maximum but with the minimum, it is returning 0.

Is there a misplacement of syntax perhaps?

import java.util.Scanner;

public class App {
    public static void main(String[] args) {

        int in;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of elements you want to store: ");
        in=sc.nextInt();  

        int array[] = new int[in];

        int min = array[0];
        int max = array[0];

            for (int i=0; i < in; i  ){
    System.out.print("Input number " (i 1) " :");
                array[i]=sc.nextInt();
                if(array[i]>max){
                    max=array[i];
                }
                else if (array[i]<min){
                    min=array[i];
                }                
            }
                sc.close();

    System.out.print(" The inputed array is "); 
            for (int i=0; i < in; i  ){  
            System.out.print(array[i] " ");
            }
    System.out.println("\n    --------------------");
    System.out.println("The highest number is: " max);
    System.out.println("The lowest number is: "  min);
        }  
    }

(also if you can, can y'all tell me how to get the index of the minimun and maximum value and print it?)

I tried different if and else if methods. I also tried nesting but I am getting the same outcome.

CodePudding user response:

When you declare an initialize your int array[]:

int array[] = new int[in];

you essentially are filling each array element with 0 by default. Then, when you declare and initialize the min and max variables with array[0] it would be the same as declaring:

int min = 0;
int max = 0;

The max variable is at a relatively low value which is good unless the User enters all signed (negative) integer values to make up the array elements in which case none of those entry values will ever max over 0 which means at the end, max will be 0 which is also wrong.

The same theory applies to the min variable. Since the min variable already holds a low value of 0 (initialized as such), the only way an element value within the array[] Array will be lower is if the array actually contained a signed (negative) value. If it doesn't the the already held value in min will remain to be the lowest value...which as you know will be in most cases wrong.

The thing to do in this particular use-case would be to initialize the min variable with a value which would be the largest a int data type can hold:

int min = Integer.MAX_VALUE;

You would be pretty much guaranteed that a value within the int[] array will never exceed Integer.MAX_VALUE and that if there is a element within the array that is lower, min will end up getting updated to that value.

The same should be applied to the initialization of the max variable except with the lowest possible int data type value:

int max = Integer.MIN_VALUE;

I think at this point you can understand why. ;)

So, all in all, simply change:

int min = array[0];
int max = array[0];

to this instead:

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

and all should be fine.

On A Side:

In a real world application where a User is expected to fill in values for an Array, there is no way of knowing what the User (like your instructor) may be entering to fill the elements of that array unless you code specifically to ensure a particular value range. By doing what is described above eliminates any worry of that unless the User supplies a value greater than what an int data type can accept in which case an exception would occur and the application will crash.

CodePudding user response:

You are initializing min even before taking inputs. That's why the min value is always 0 because the default initial value of int array is 0. So, the else if (array[i]<min) condition is never met because no non-negative integer can be smaller than 0.

You can try adding this in your for loop AFTER you take inputs:

if(i==0){
min = array[0];
max = array[0];
}

CodePudding user response:

You can also use type Integer (instead of int), as they can be initialized by null

Integer max = null;
Integer min = null;

In your loop:

if(max == null || max < array[i]) {
  max = array[i];
}

if(min == null || min > array[i]) {
  min = array[i];
}

CodePudding user response:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {

        int in;
        List<Integer> elements = new ArrayList<>();

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of elements you want to store: ");
        in=sc.nextInt();

        for (int i=0; i < in; i  ){
            System.out.print("Input number " (i 1) " :");
            elements.add(sc.nextInt());
        }
        sc.close();

        List<Integer> unsorted = new ArrayList<>(elements);
        Collections.sort(elements);

        int max = elements.get(elements.size()-1);
        int min = elements.get(0);

        System.out.println("\n    --------------------");
        System.out.println("The highest number is: " max);
        System.out.println("The lowest number is: "  min);
        System.out.println("Index of Min Value is : " unsorted.indexOf(min));
        System.out.println("Index of Max Value is : " unsorted.indexOf(max));
    }
}
  •  Tags:  
  • java
  • Related