Write a Java program that declares three variables of int type, q, d, and n, to
represent a set of number of coins a user must insert in order to buy a pack of cookie from the vending machine.
Use three nested while loops (must be while loops) to display all possible combinations of q, d, and n, as shown below.
You need to use an if statement within inner-most while loop to evaluate a Boolean condition based on the formula: 0.25q + 0.1d + 0.05n = 0.65.
public class Coins {
public static void main(String[] args) {
int q = 10;
int d = 6;
int n = 12;
int loopQ = q;
int loopD = d;
int loopN = n;
while (loopQ > 0) {
while (loopD > 0) {
while (loopN > 0) {
System.out.println(String.format("A new combination of: q: %s, d: %s, n: %s. Final value: %s",
loopQ, loopD, loopN, (0.25 * loopQ + 0.1 * loopD + 0.05 * loopN)));
if (0.25 * loopQ + 0.1 * loopD + 0.05 * loopN == 0.65) {
System.out.println(
String.format("Possible combination of: q: %s, d: %s, n: %s", loopQ, loopD, loopN));
}
loopN -= 1;
}
loopD -= 1;
loopN = n;
}
loopQ -= 1;
loopD = d;
}
}
}
Comments
Leave a comment