Originally Posted by
SisyphusTheCoder
Hello guys! Need your help with something. I'm tasked to find an issue/mistake in this program that is supposed to take any amount entered in the console and exchange that amount of money for coins of different values. The program seems to work fine and accomplishes the task. I have been staring at it for 2 days now and have come up with nothing. Any help would be much appreciated! Best regards and thank you!
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Please enter the amount of coins you want to exchange: ");
int coinsLeft = keyboardInput.nextInt();
System.out.println("Your coin amount is: " + coinsLeft);
System.out.println("\n\nYou'll get: ");
int twoEuros = coinsLeft / 200;
coinsLeft = coinsLeft % 200;
if (twoEuros > 0){
System.out.println(twoEuros + " <=== 2 euro coin(s)");}
int oneEuro = coinsLeft / 100;
coinsLeft = coinsLeft % 100;
if (oneEuro > 0){
System.out.println(oneEuro + " <=== 1 euro coin(s)");}
int fiftyCents = coinsLeft / 50;
coinsLeft = coinsLeft % 50;
if (fiftyCents > 0){
System.out.println(fiftyCents + " <=== 50 cent coin(s)");}
int twentyCents = coinsLeft / 20;
coinsLeft = coinsLeft % 20;
if (twentyCents > 0){
System.out.println(twentyCents + " <=== 200 cent coin(s)");}
int tenCents = coinsLeft / 10;
coinsLeft = coinsLeft % 10;
if (tenCents > 0){
System.out.println(tenCents + " <=== 100 cent coin(s)");}
int fiveCents = coinsLeft / 5;
coinsLeft = coinsLeft % 5;
if (fiveCents > 0){
System.out.println(fiveCents + " <=== 5 cent coin(s)");}
int twoCents = coinsLeft / 2;
coinsLeft = coinsLeft % 2;
if (twoCents > 0){
System.out.println(twoCents + " <=== 2 cent coin(s)");}
int oneCent = coinsLeft;
if (coinsLeft > 0){
System.out.println(oneCent + " <=== 1 cent coin(s)");}
}
System.out.println(twentyCents + "
<=== 200 cent coin(s)");}
int tenCents = coinsLeft / 10;
coinsLeft = coinsLeft % 10;
if (tenCents > 0){
System.out.println(tenCents + "
<=== 100 cent coin(s)");}
int fiveCents = coinsLeft / 5;
coinsLeft = coinsLeft % 5;
if (fiveCents > 0){
Seems like I overthought this one. Turns out that there were 2 simple typos in the code which didn't affect the function of the code itself and just the print outs. I guess a lesson learned - keep it simple and don't overthink it.
Originally Posted by
Norm
Why do you think there is any problem with the code?
What happens when you run the code with different input values?
For easier testing, add a loop around the code that reads the number and displays the results.
Then change the Scanner class's constructor(outside of the loop) to preload a number of input values:
Scanner keyboardInput = new Scanner("1 234 678 543 333 23 -99 0 100000");
I tried out what you said and learned quite a bit in the process about loops. Thanks for putting in the effort and time to reply to post. Have a good one.