I have a second program due tomorrow and I have been working non stop to try to understand why some numbers work and others don’t.
The general idea is that a person enters an amount of ‘change’, the program will run and separate that change into ‘quarters’, ‘dimes’, ‘nickels’, and ‘pennies’. and this will keep happening until the person enters a zero instead of an integer. (Ignore the fact of the user inserting negative, or decimals. I just need this in int.)
My problem is that it’s not processing these numbers: (1,2,3,4, 20,21,22,23,24,25,26,27,28,29,… etc.) Why?
Here is my code:
import java.util.Scanner; //I have established and imported the Scanner in this line!
public class Main{
public static void main(String[] args) {
// bellow is where the variables are declared!
int change = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
// change inquiry in the following line
System.out.println("Please Enter an amount of change greater than zero or enter Zero to exit: ");
//declaring the scanner variable and preparing it for use
Scanner myObj = new Scanner(System.in);
change = myObj.nextInt(); //change input is inserted by user
//if the change is not equal to zero then it will
//seperate the nuber into its respective coin count.
while (change != 0){
while (change >= 25){
change = change - 25;
quarters = quarters + 1;
}
while (change >= 10){
change = change - 10;
dimes = dimes + 1;
}
while (change >= 5){
change = change - 5;
nickels = nickels + 1;
pennies = change;
//finally ready to show the work the
//computer performed with these print statements
System.out.println("There are (is): " + quarters +" quarter(s),");
System.out.println(dimes + " dime(s), ");
System.out.println(nickels + " nickel(s), and ");
System.out.println(pennies + pennies + " pennies left");
}
//this question will continue to be
//asked untill
//Zero is entered which will then end
//the program.
System.out.println("Please Enter a new amount of change greater than zero or enter Zero to exit: ");
change = myObj.nextInt();
}
}
}
>Solution :
First of all, the nickels loop should only calculate for nickels, not output the result.
Second, the values of each coin are not reset, so they will accumulate over time.
Here’s an example of how you can do it:
while (change >= 5){
change = change - 5;
nickels = nickels + 1;
}
And then reset the values, and then you should be good.