Home > Software engineering >  How to return an empty array Java
How to return an empty array Java

Time:04-21

Hi, how are you? =) I'm new to Java, currently, I'm learning arrays and loops, and I'm really struggling with them at the moment.

Here is my homework: Write a public method int[] findMinMaxPrices(int[] price). It takes an array of prices and returns a new array.

Empty, if the array is empty. Returns only one element, if the maximum and minimum prices in the prices array are the same. Returns only two elements if the price array contains both the minimum and maximum prices. The minimum price should go first, then the maximum.

Only for loop can be used.

I would use some help here: How to return an empty array in this case? I made it many times in draft, unfortunately, it doesn't work here.

How can I use a for loop here?

Can you give me some hints or advice?

Thank you in advance!)

import java.util.Arrays;

public class QuadraticEquationSolver {
    
        public int[] findMinMaxPrices(int[] prices) { // I know it's a mess, but I'm just learning =)
        
        Arrays.sort(prices);
        
        int empty [] = {};
        int first [] = Arrays.copyOf(prices, 1);
        
        int a = prices[0];
        int b = prices[prices.length-1];
        
        int second [] = new int[] {a,b};        
        
            if(prices[0] == prices[prices.length-1]) {
                    return first;
            }   
            else if(prices[0] < prices[prices.length-1]) {
                    return second;
                        
            }else{ 
                return empty;
                //return new int[0]; I tried to use this here, didn't work =(
            }       
    }
   
    public static void main(String[] args) {
        QuadraticEquationSolver shop = new QuadraticEquationSolver();

        //Should be [50, 1500]
        int[] prices = new int[] {100, 1500, 300, 50};
        int[] minMax = shop.findMinMaxPrices(prices);
        System.out.println(Arrays.toString(minMax));

//findMaxPrices(new int[] {10, 50, 3, 1550}), returns [3, 1550]
//findMaxPrices(new int[] {}), returns []
//findMaxPrices(new int[] {50, 50}), returns [50]


    }
}

CodePudding user response:

You return an empty array the same way you create an empty array when you call findMaxPrices(new int[]{}), just use new int[]{}.

For your requirement you don't need to sort the array, because you can store the minimum and maximum value in a local variable and just add minimum before maximum to the array that you return.

One essential thing you are missing is checking for the array length of prices. Using prices.length you get how many values are in the array. Always check the length of an array before you try to access it using an index, otherwise you risk getting an IndexOutOfBounds exception. Using this you can immediately return when prices.length == 0 because then there are no values in the array and you need to return an empty array. If prices.length == 1 we only have one value in the array. This value must be minimum and maximum so we can return an array containing this value. In all other cases we can use a for loop to loop over all elements in the array. If we find a value that is smaller/ greater than the current minimum/ maximum we set that as new maximum. For this to work we need to initialize minimum and maximum to the biggest/ smallest possible value first. Java has the constants Integer.MAX_VALUE and Integer.MIN_VALUE for this kind of thing. Last but not least we need to check if maximum and minimum are the same. In that case we only return one element, otherwise we return both, but minimum before maximum.

public class Application {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(findMinMaxPrices(new int[]{100, 1500, 300, 50})));
        System.out.println(Arrays.toString(findMinMaxPrices(new int[]{})));
        System.out.println(Arrays.toString(findMinMaxPrices(new int[]{50, 50})));
    }

    public static int[] findMinMaxPrices(int[] prices) {
        // we can simply check the array length. If it is zero we return an empty array
        if(prices.length == 0) return new int[]{};
        else if(prices.length == 1) return new int[prices[0]]; // if we only have one element that one element must be the minimum and maximum value
        // array length is not zero or one -> we need to find minimum and maximum
        int min = Integer.MAX_VALUE; // set to maximal possible int value
        int max = Integer.MIN_VALUE; // set to minimal possible int value
        for (int i = 0; i < prices.length; i  ) {
            int currentPrice = prices[i];
            if(currentPrice < min) min = currentPrice;
            if(currentPrice > max) max = currentPrice;
        }
        // now we have minimum and a maxium value
        // if they are the same only return one value
        if(min == max) return new int[]{max};
        // otherwise return both, but minumum first
        return new int[]{min, max};
    }
}

Expected output:

[50, 1500]
[]
[50]
  • Related