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