Issue
Hi guys. How are you? =)
I'm new to Java and currently
I have a task to create a method, it takes one parameter sum - the amount of money to be given out, and returns the minimum number of banknotes that can be given out this amount.
I made it with for loop, but I can't find where I made mistake in while loop. Could you please give me hint or advice? Thank you!
public class ATM {
public static int countBanknotes(int sum) {
int[] notes = new int[] { 500, 200, 100, 50, 20, 10, 5, 2, 1 };
int[] noteCounter = new int[9];
int amount = 0;
for (int i = 0; i < 9; i++) {
if (sum >= notes[i]) {
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
}
for (int i = 0; i < 9; i++) {
if (noteCounter[i] != 0) {
amount += noteCounter[i];
}
}
return amount;
}
public static void main(String[] args) {
// 6 (500 + 50 + 20 + 5 + 2 + 1
int sum = 578;
System.out.print(ATM.countBanknotes(sum));
}
}
And while loop
public class JustATest {
public static int countBanknotes(int sum) {
int[] notes = new int[] { 500, 200, 100, 50, 20, 10, 5, 2, 1 };
int[] noteCounter = new int[9];
int amount = 0;
int i = 0;
while ( i < 9 ) {
if (sum >= notes[i]) {
i++;
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
}
while ( i < 9 ) {
if (noteCounter[i] != 0) {
i++;
amount += noteCounter[i];
}
}
return amount;
}
public static void main(String[] args) {
// Should be 6 (500 + 50 + 20 + 5 + 2 + 1)
int sum = 578;
System.out.print(JustATest.countBanknotes(sum));
}
}
Solution
You need to reinitialize your i
variable between the loops, or use another variable, like j
.
Furthermore, you should not have your i++
inside the if statements in your while loops. Otherwise, there are scenarios where the counter is never incremented and you will have an endless loop. That is bad!
Put your i++
in the bottom of the while loop outside the if statement like this:
while ( i < 9 ) {
if (sum >= notes[i]) {
noteCounter[i] = sum / notes[i];
sum -= noteCounter[i] * notes[i];
}
i++;
}
int j = 0;
while ( j < 9 ) {
if (noteCounter[j] != 0) {
amount += noteCounter[j];
}
j++;
}
This way, the counters are always incremented no matter what, and you will not have endless loops. I included a fix for your problem in the code above as well.
Answered By - Pogoe
Answer Checked By - Marilyn (JavaFixing Volunteer)