I have the following task, write a method that takes a list of prices and sums them up, including only those that are greater than minPrice (inclusive) and less than maxPrice (inclusive), and returns the amount.
Only for loop can be used.
And I have a wrong result in return.
I presume that I have a mistake in if (price >= minPrice && price <= maxPrice) counter ;
But I do not understand why.
public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
if (prices.length == 0) return 0;
int counter = 0;
for(int i = 0; i < prices.length; i ) {
int price = prices[i];
if (price >= minPrice && price <= maxPrice) counter ;
}
int result [] = new int [counter];
int newResult = 0;
for(int i = 0; i < result.length; i ) {
newResult = prices[i];
}
return newResult;
}
public static void main(String[] args) {
QuadraticEquationSolver shop = new QuadraticEquationSolver();
//Should be 144 - 20 50 40 34
int[] prices = new int[] {10, 20, 50, 40, 34, 500};
System.out.println(shop.getPricesSum(prices, 20, 50));
}
}
The result is 120. I suppose it calculates only the first four indexes of the array.
CodePudding user response:
Why do you increment a counter? You've just get the NUMBER of correct elements, but then you're iterating from the first (0) one. Instead, you can sum it up already in the first foor loop like this:
for(int i = 0; i < prices.length; i ) {
int price = prices[i];
if (price >= minPrice && price <= maxPrice) newResult = price;
}
CodePudding user response:
public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
int sum = 0;
for (int price : prices) {
if (price >= minPrice && price <= maxPrice) {
sum = price;
}
}
return sum;
}
CodePudding user response:
That first bit where you were counting the number of prices within minPrice and maxPrice wasn't useful at all. Plus, declaring that second array sized with the number of prices contained within your range didn't help you in computing the sum of prices.
Right now, you just need to determine the sum of prices within your range. Counting is not part of your goal neither helping you with it. Before starting to code, always think about the steps you need to take to achieve your goal.
I think this is what you were attempting to do:
public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
int newResult = 0;
for(int i = 0; i < prices.length; i ) {
if (prices[i] >= minPrice && prices[i] <= maxPrice){
newResult = prices[i];
}
}
return newResult;
}
public static void main(String[] args) {
QuadraticEquationSolver shop = new QuadraticEquationSolver();
//Should be 144 - 20 50 40 34
int[] prices = new int[] {10, 20, 50, 40, 34, 500};
System.out.println(shop.getPricesSum(prices, 20, 50));
}