Java input;
import java.util.*;
public class NetPay3
{
public static void main()
{
// Define Scanner object
Scanner inLine = new Scanner (System.in);
// Define other variables
float pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds,
OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
// Ask for the time in seconds
System.out.print ("Enter Net Pay : ");
pay = inLine.nextFloat();
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OneHundredPounds = (int) pay / 100;
// Calculate what is left over and store back into seconds
pay = pay % 100;
// Calculate the minutes. There are 60 seconds
// in a minute.
FiftyPounds = (int) pay / 50;
// Whatever is left over must be the seconds
pay = pay % 50;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
TwentyPounds = (int) pay / 20;
// Calculate what is left over and store back into seconds
pay = pay % 20;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FivePounds = (int) pay / 5;
// Calculate what is left over and store back into seconds
pay = pay % 5;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
OnePound = (int) pay / 1;
// Calculate what is left over and store back into seconds
pay = pay % 1;
// Calculate the hours. There are (3600)
// i.e. 60 x 60 seconds in every hour
FiftyPence = (int) pay / 2;
// Calculate what is left over and store back into seconds
pay = pay % 2;
// Display the hours, minutes and seconds
System.out.println ("Amount of £100 notes " + OneHundredPounds);
System.out.println ("Amount of £50 notes " + FiftyPounds);
System.out.println ("Amount of £20 notes " + TwentyPounds);
System.out.println ("Amount of £5 notes " + FivePounds);
System.out.println ("Amount of £1 coins " + OnePound);
System.out.println ("Amount of 50p coins " + FiftyPence);
}
}
Screen input and output;
Enter Net Pay : 176.50
Amount of £100 notes 1
Amount of £50 notes 1
Amount of £20 notes 1
Amount of £5 notes 1
Amount of £1 coins 1
Amount of 50p coins 0
Hi relatively new to programming,
having trouble with me modulus and int operators in terms of getting them to function with the correct output on screen, previous syntax's worked correctly bar the 50p, anyone care to shed any light? thanks :)
Try changing FiftyPence = (int) pay / 2; toFiftyPence = (int) (pay / 0.5f);
Here is your code corrected and improved.
Don't use floats here, use integer arithmetic.
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
// Define Scanner object
Scanner inLine = new Scanner(System.in);
// Define other variables
int pay;
int OneHundredPounds, FiftyPounds, TwentyPounds, FivePounds, OnePound, FiftyPence, TwentyPence, FivePence, TwoPence, OnePenny;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
OneHundredPounds = (int) pay / 10000;
pay = pay % 10000;
FiftyPounds = (int) pay / 5000;
pay = pay % 5000;
TwentyPounds = (int) pay / 2000;
pay = pay % 2000;
FivePounds = (int) pay / 500;
pay = pay % 500;
OnePound = (int) pay / 100;
pay = pay % 100;
FiftyPence = (int) pay / 50;
pay = pay % 50;
System.out.println("Amount of £100 notes " + OneHundredPounds);
System.out.println("Amount of £50 notes " + FiftyPounds);
System.out.println("Amount of £20 notes " + TwentyPounds);
System.out.println("Amount of £5 notes " + FivePounds);
System.out.println("Amount of £1 coins " + OnePound);
System.out.println("Amount of 50p coins " + FiftyPence);
System.out.println("Leftover pence: " + pay);
}
}
But I would further simplify this to (for example) this program:
import java.util.*;
public class NetPay3 {
public static void main(String[] args) {
Scanner inLine = new Scanner(System.in);
float[] val = new float[]{100, 50, 20, 5, 1, 0.5f, 0.2f, 0.05f, 0.02f, 0.01f};
int pay;
System.out.print("Enter Net Pay : ");
float pay1 = inLine.nextFloat();
pay = (int) (100 * pay1);
for (int i=0; i<val.length; i++){
int m = ((int)(val[i] * 100));
int cnt = pay / m;
String s1 = val[i] < 1 ? " coins: " : " notes: ";
String s2 = val[i] < 1 ? "" : "£";
String s3 = val[i] < 1 ? "p" : "";
String s4 = val[i] < 1 ? m + "" : (m/100) + "";
System.out.println("Amount of " + s2 + s4 + s3 + s1 + cnt);
pay = pay % m;
}
}
}
Related
I am attempting to write a program that will list the amount of kilograms, grams, and milligrams in a given input. Ex. in the given input of 1050042mg, the output will say that there is 1 kilogram, 50 grams, and 42 milligrams.
import java.util.Scanner;
class milligrams {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int milligram;
double kilo, gram;
System.out.println("Enter the weight in milligrams: ");
milligram = in.nextInt();
kilo = milligram / 1000000;
gram = milligram / 10000;
milligram = milligram / 1;
System.out.println("The weight is " + kilo + "kilos, " + gram + "grams" + milligram + " milligrams");
}
}
The part I am struggling with is I believe I must change the 10-12 lines with code that will read the given user input and then divide the input by the appropriate number to get kg, g, and mg but I cannot figure out how to do it as I am new to java. I am aware the division numbers are incorrect but I don't believe that is the issue. If this is not the right approach please guide me to the right approach.
You can use the modulus (clock arithmetic) operator
const KG = 1000000;
const GRAM = 1000;
Scanner in = new Scanner(System.in);
int milligram;
double kilo, gram;
System.out.println("Enter the weight in milligrams: ");
milligram = in.nextInt();
kilo = milligram / KG;
//use the modulus here (and below)
milligram = milligram % KG;
gram = milligram / GRAM;
// 2nd use of modulus, this time with GRAN
milligram = milligram % GRAM;
System.out.println("The weight is " + kilo + "kilos, " + gram + "grams" + milligram + " milligrams");
}
I am pretty new to java and am trying to create a simple program that converts an amount of money into change. However, I find that the program always prints one penny less than necessary.
I would have just added 1 to my pennies variable before printing but this would mean that when change is 0, it would still add a penny as change.
Here is my code:
change = amtPaid-Math.round((total*1.13)*100)/100.0;
pennies = (int) (change * 100);
twenties = (int)(pennies/2000);
pennies %= 2000;
tens = (int)(pennies/1000);
pennies %= 1000;
fives = (int)(pennies/500);
pennies %= 500;
toonies = (int)(pennies/200);
pennies %= 200;
loonies = (int)(pennies/100);
pennies %= 100;
quarters = (int)(pennies/25);
pennies %= 25;
dimes = (int)(pennies/10);
pennies %= 10;
nickels = (int)(pennies/5);
pennies %= 5;
I get this output after providing sample input:
The change will be: 1.83
To make up this amount, you will need:
0 twenty-dollar bills 0 ten-dollar bills
0 five-dollar bills 0 toonies
1 loonies 3 quarters
0 dimes 1 nickels
2 pennies
Does anyone know why this may be happening and how to fix it?
The way I see it, get your Grand Total (cost and taxes all in) to a decimal precision of no more than 2 (ie: 55.28). Don't allow the decimal precision to be more than 2. Whatever the rounding mechanism you use, make sure your happy with the final result.
Subtract the Amount Owed from the Amount Paid and make sure the final result is to a decimal precision of 2 (ie: 60.00 - 55.2814 = 4.7186 = 4.72 {rounded-up}). By not rounding properly to a decimal precision of 2 is where you can loose or gain a penny when calculating returned change.
Break the Amount To Return into Dollars and Cents. Both should be integer values (ie: 4 Dollars and 72 Cents).
// A value for the sake of this example. Taxes Included!
double totalOwed = 52.26534;
// Round to a precision of 2 (round UP on .5)
double grandTotal = BigDecimal.valueOf(totalOwed)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
// A value for the sake of this example.
double amountPaid = 60.00;
// Round to a precision of 2 (round UP on .5)
double returnValue = BigDecimal.valueOf(amountPaid - grandTotal)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
int dollars = Integer.parseInt(String.valueOf(returnValue).split("\\.")[0]);
int cents = Integer.parseInt(String.valueOf(returnValue).split("\\.")[1]);
Work out the bill currency to be returnd and add it to a List for display later. There are a LOT of different ways to do this. Here is one way:
List<String> change = new ArrayList<>();
int returnVal;
// Some displayable information
change.add("Total Cost: --> " + String.valueOf(grandTotal));
change.add("Total Paid: --> " + String.valueOf(amountPaid));
change.add("Return change: --> " + String.valueOf(returnValue));
// 100 Dollar Bills
if (dollars >= 100) {
returnVal = dollars / 100;
change.add(" " + String.valueOf(returnVal) + " Hundred Dollar Bill(s)");
dollars -= (returnVal * 100);
}
// 50 Dollar Bills
if (dollars >= 50) {
returnVal = dollars / 50;
change.add(" " + String.valueOf(returnVal) + " Fifty Dollar Bill(s)");
dollars -= (returnVal * 50);
}
// 20 Dollar Bills
if (dollars >= 20) {
returnVal = dollars / 20;
change.add(" " + String.valueOf(returnVal) + " Twenty Dollar Bill(s)");
dollars -= (returnVal * 20);
}
// 10 Dollar Bills
if (dollars >= 10) {
returnVal = dollars / 10;
change.add(" " + String.valueOf(returnVal) + " Ten Dollar Bill(s)");
dollars -= (returnVal * 10);
}
// 5 Dollar Bills
if (dollars >= 5) {
returnVal = dollars / 5;
change.add(" " + String.valueOf(returnVal) + " Five Dollar Bill(s)");
dollars -= (returnVal * 5);
}
// 2 Dollar Bills
if (dollars >= 2) {
returnVal = dollars / 2;
change.add(" " + String.valueOf(returnVal) + " Two Dollar Bill(s)");
dollars -= (returnVal * 2);
}
// 1 Dollar Bills
if (dollars >= 1) {
returnVal = dollars / 1;
change.add(" " + String.valueOf(returnVal) + " One Dollar Bill(s)");
dollars -= (returnVal * 1);
}
// Quarters (working against cents now)
if (cents >= 25) {
returnVal = cents / 25;
change.add(" " + String.valueOf(returnVal) + " Quarter(s)");
cents -= (returnVal * 25);
}
// Dimes
if (cents >= 10) {
returnVal = cents / 10;
change.add(" " + String.valueOf(returnVal) + " Dime(s)");
cents -= (returnVal * 10);
}
// Nickles
if (cents >= 5) {
returnVal = cents / 5;
change.add(" " + String.valueOf(returnVal) + " Nickle(s)");
cents -= (returnVal * 5);
}
// Pennies
if (cents >= 1) {
returnVal = cents / 1;
change.add(" " + String.valueOf(returnVal) + " Pennies");
cents -= (returnVal * 1);
}
// Display the Change-Back in Console Window
for (String str : change) {
System.out.println(str);
}
As you can see there is a lot of repetitious code in the example above. You can get rid of this by doing it yet another way. You can utilize an Array or Collection mechanism to hold the Dollar and coin denominations, for example:
// A value for the sake of this example. Taxes Included!
double totalOwed = 52.26534;
// Round to a precision of 2 (round UP on .5)
double grandTotal = BigDecimal.valueOf(totalOwed)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
// A value for the sake of this example.
double amountPaid = 60.00;
// Round to a precision of 2 (round UP on .5)
double returnValue = BigDecimal.valueOf(amountPaid - grandTotal)
.setScale(2, RoundingMode.HALF_UP).doubleValue();
int dollars = Integer.parseInt(String.valueOf(returnValue).split("\\.")[0]);
int cents = Integer.parseInt(String.valueOf(returnValue).split("\\.")[1]);
List<String> change = new ArrayList<>();
int returnVal;
// Using arrays (or a collection mechanism) like this
// allows you to set whatever denominations you like.
String[][] dollarDenominations = {
{"100", " Hundred Dollar Bill(s)"},
{"50" , " Fifty Dollar Bill(s)" },
{"20" , " Twenty Dollar Bill(s)" },
{"10" , " Ten Dollar Bill(s)" },
{"5" , " Five Dollar Bill(s)" },
{"2" , " Two Dollar Bill(s)" },
{"1" , " One Dollar Bill(s)" }
};
// Although not commonly used, you might even want to
// add 50 cent pieces to the Array.
String[][] coinDenominations = {
{"25", " Quarter(s)"},
{"10", " Dime(s)" },
{"5" , " Nickle(s)" },
{"1" , " Pennies" }
};
// Some displayable information
change.add("Total Cost: --> " + String.valueOf(grandTotal));
change.add("Total Paid: --> " + String.valueOf(amountPaid));
change.add("Return change: --> " + String.valueOf(returnValue));
// Dollar Denominations
for (int i = 0; i < dollarDenominations.length; i++) {
int denom = Integer.parseInt(dollarDenominations[i][0]);
String typeString = dollarDenominations[i][1];
if (dollars >= denom) {
returnVal = dollars / denom;
change.add(" " + String.valueOf(returnVal) + typeString);
dollars -= (returnVal * denom);
}
}
// Coin Denominations
for (int i = 0; i < coinDenominations.length; i++) {
int denom = Integer.parseInt(coinDenominations[i][0]);
String typeString = coinDenominations[i][1];
if (cents >= denom) {
returnVal = cents / denom;
change.add(" " + String.valueOf(returnVal) + typeString);
cents -= (returnVal * denom);
}
}
// Display the Change-Back data in Console Window...
for (String str : change) {
System.out.println(str);
}
As said before, there are several other ways to do this sort of thing. The important thing is to work against Change-Back values that are to 2 decimal places. After all...to my knowledge, there is no such denomination as a one-sixth penny (there is no denomination for mills). The US at one time (between 1793 and 1857) use to have a half-Penny but that no longer exists and never ever will again for obvious reasons. In Canada there is no Penny since it costs almost 2 cents to make one and ultimately (in my opinion) the United States will most likely follow this scheme and save millions upon millions in the process since it also costs approx. 1.82+ cents to make a US penny.
I'm going through ThinkJava Version 6.1.0 (latest) and in Chapter 2 Exercise 2.3, I'm stuck on #5 which asks "Calculate and display the percentage of the day that has passed. You might run into problems when computing percentages with integers, so consider using floating-point."
I've attempted to get the percentage, but I'm not getting the right result.
I've completed the first 4 questions. Here is what I have so far:
public class Date {
public static void main(String[] args) {
int hour = 13, minute = 58, second = 45;
double percentage;
double secondsSinceMidnight = second + (minute * 60) + (hour * 3600);
double secondsRemainingInDay = (60-second) + ((60-1-minute)*60) + (24-1-hour)*3600;
percentage = (secondsSinceMidnight * 100) / 60;
System.out.println("Number of seconds since midnight:");
System.out.println(secondsSinceMidnight);
System.out.println("Number of seconds remaining in the day:");
System.out.println(secondsRemainingInDay);
System.out.println("Percentage of the day past:");
System.out.println(percentage + "%");
}
}
Thank you for your help and support!
Please check the formula for calculating the percentage of the day already past.
percentage = (secondsSinceMidnight * 100) / 60;
Does not seem right to me. It should be something like
percentage = 100 * secondsSinceMidnight / totalSecondsInDay;
totalSecondsInDay can be the sum of secondsRemainingInDay and secondsSinceMidnight
i think your code have problems with type-casting
in line 3 exchange int with double:
double hour = 13, minute = 58, second = 45;
or there is problem with constant numbers , write numbers in this way : 60.0 instead of 60
Here's an example with a hardcoded time. It's in military time obviously so keep that in mind.
public class Time
{
public static void main(String[] args) {
int startHour = 12; //when you start editing program
int startMinute = 00;
int startSecond = 00;
System.out.print("Number of seconds since midnight: ");
startMinute = (startHour * 60 + startMinute );
startSecond = (startMinute * 60 + startSecond);
System.out.print(startSecond);
System.out.println(" seconds");
int secondInADay = 86400; //number of seconds in a day
System.out.print ("Seconds remaining in the day: ");
System.out.println (secondInADay - startSecond);
System.out.print("Percent of the day that has passed: ");
double startSeconds = 43200; //number of seconds that have passed in a day at start of editing program
System.out.println(startSeconds * 100 / 86400);
int endHour = 16; //time when finished editing program
int endMinute = 00;
int endSecond = 00;
System.out.print ("Difference = "); //difference in time from start to finish
endMinute = (endHour * 60 + endMinute );
endSecond = (endMinute * 60 + endSecond);
System.out.print (endSecond - startSecond);
System.out.print (" seconds");
}
}
I need to select a value based on a percentage chance of that value being selected. For example:
10% of the time increment value a
20% of the time increment value b
30% of the time increment value c
40% of the time increment value d
The percentages will always add up to exactly 100%
I have encountered several solutions like this one, but have determined that they cannot possibly be correct. Here is a sample program built using the solution mentioned:
import java.util.Random;
public class Main {
private static Random r = new Random();
public static void main(String[] args) {
final int iterations = 1000000;
System.out.println("Testing percentage based random, " + iterations + " iterations");
int onePercent = 0;
int sixPercent = 0;
int sevenPercent = 0;
int thirtySixPercent = 0;
int fiftyPercent = 0;
// Those values add up to 100% overall
for (int i = 0; i < iterations; i++) {
int random = r.nextInt(100);
if (random < 1) {
onePercent++;
continue;
}
if (random < 6) {
sixPercent++;
continue;
}
if (random < 7) {
sevenPercent++;
continue;
}
if (random < 36) {
thirtySixPercent++;
continue;
}
if (random < 50) {
fiftyPercent++;
continue;
}
// That can't be right because if random > 50 then nothing at all happens
}
System.out.println("One percent happened about " + (onePercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Six percent happened about " + (sixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Seven percent happened about " + (sevenPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Thirty six percent happened about " + (thirtySixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Fifty percent happened about " + (fiftyPercent / Float.valueOf(iterations)) * 100 + "% of the time");
}
}
Output:
Testing percentage based random, 1000000 iterations
One percent happened about 0.99649996% of the time
Six percent happened about 4.9925% of the time
Seven percent happened about 1.0029999% of the time
Thirty six percent happened about 29.001299% of the time
Fifty percent happened about 14.0191% of the time
Expected output:
Testing percentage based random, 1000000 iterations
One percent happened about 0.99649996% of the time
Six percent happened about 6.9925% of the time
Seven percent happened about 7.0029999% of the time
Thirty six percent happened about 36.001299% of the time
Fifty percent happened about 50.0191% of the time
I believe I need to use some sort of algorithm to convert the percentages into a scale from 0 to 99 so that the random number generator can select a value accurately. I cannot think of how to do that, though.
Your results are correct :
Fifty percent happened about 14.0191% of the time
50 - 36 = 14
Thirty six percent happened about 29.001299% of the time
36 - 7 = 29
Seven percent happened about 1.0029999% of the time
7 - 6 = 1
....
Delete all 'continue' statements if you want them to sum up.
Figured it out. You need to keep track of the percentage tested so far and add it to the current test.
import java.util.Random;
public class Main {
private static Random r = new Random();
public static void main(String[] args) {
final int iterations = 1000000;
System.out.println("Testing percentage based random, " + iterations + " iterations");
int onePercent = 0;
int sixPercent = 0;
int sevenPercent = 0;
int thirtySixPercent = 0;
int fiftyPercent = 0;
// Those values add up to 100% overall
for (int i = 0; i < iterations; i++) {
int random = r.nextInt(100);
int totalPercent = 0;
if (random < totalPercent + 1) {
onePercent++;
continue;
}
totalPercent += 1;
if (random < totalPercent + 6) {
sixPercent++;
continue;
}
totalPercent += 6;
if (random < totalPercent + 7) {
sevenPercent++;
continue;
}
totalPercent += 7;
if (random < totalPercent + 36) {
thirtySixPercent++;
continue;
}
totalPercent += 36;
if (random < totalPercent + 50) {
fiftyPercent++;
continue;
}
totalPercent += 50;
// That can't be right because if random > 50 then nothing at all happens
}
System.out.println("One percent happened about " + (onePercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Six percent happened about " + (sixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Seven percent happened about " + (sevenPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Thirty six percent happened about " + (thirtySixPercent / Float.valueOf(iterations)) * 100 + "% of the time");
System.out.println("Fifty percent happened about " + (fiftyPercent / Float.valueOf(iterations)) * 100 + "% of the time");
}
}
I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?