Question:

Need help with java programming I think I am getting close, but still a bit lost?

by  |  earlier

0 LIKES UnLike

If input is 0, your output should be:

Your amount is zero

If input is -2000.25, your output should be:

Your amount is negative

If input is 23.67, your output should be:

Your amount 23.67 consists of

23 dollars

2 quarters

1 dime

1 nickel

2 pennies

this is my attempt at it any help would be greatly appreciated

______________________________________...

import javax.swing.JOptionPane;

public class homework3 {

public static void main(String[] args) {

double number;

double dollar = 1;

double quarter = .25;

double dime = .10;

double nickel = .05;

double penny = .01;

double numDollars = 0;

double numQuarters = 0;

double numDimes = 0;

double numNickels = 0;

double numPennies = 0;

String input = JOptionPane.showInputDialog

("Please enter the amount.");

number = Double.parseDouble(input);

double total = number;

while(number > 0){

if(number - dollar>= 0){

numQuarters ++;

total -= dollar;

continue;

}

if(number - quarter>= 0){

numQuarters ++;

total -= quarter;

continue;

}

if(number - dime >= 0){

numDimes ++;

total -= dime;

continue;

}

if(number - nickel >= 0){

numNickels ++;

total -= nickel;

continue;

}

if(number - penny >= 0){

numPennies ++;

total -= penny;

continue;

}

if ( total == 0 ){ break;

}

JOptionPane.showMessageDialog( null, "The amount $" + number + "consist of/n" + numDollars + " Dollars/n" + numQuarters +" Quarters/n" + numDimes + " Dimes/n" + numNickels + " Nickels/n"+ numPennies + " Pennies");

System.exit(0);

}

if( number == 0.0) {

JOptionPane.showMessageDialog( null,"No Change");

}

else if( number < 0.0) {

JOptionPane.showMessageDialog( null,"Amount is Negative");

}

else

JOptionPane.showMessageDialog( null,"not working");

System.exit(0);

}

}

 Tags:

   Report

1 ANSWERS


  1. i think you have the idea right. i&#039;ve optimized the code a bit, though - here&#039;s the main things i did:

    - moved the if-elseif-else block above the while loop to eliminate one unnecessary comparison test

    - made the &quot;while&quot; loop a &quot;do-while&quot; instead, which eliminates another comparison test.

    - took the &quot;continue&quot; out of the last if block, which eliminates the very last iteration of the loop.

    - moved the test for the &quot;total&quot; variable into the loop control area, to keep similar things together

    note: i have NOT checked to see if this code compiles and runs - but it should.

    click the link below to see the properly-formatted code.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.