I've recently embarked into Java programming and consider myself a programming novice. It seem that I'm having an issue with my source code arithmetic. I have verified all the nested if-else statements and they all work up to the final else statement's arithmetic. It doesn't calculating correctly I have set the arithmetic up just as the above if-else statements.
the else statement is suppose to subtract 40 from the amount and then apply 1 percent charge. I have tried for the else statement fee = ((checkAmount - 40) * .01) and fee = ((checkAmount * .01) - 40)
This is just an exercise from the book
import java.util.Scanner;
public class ServiceCharge {
public static void main(String[] args)
{
double checkAmount;
double fee;
Scanner kb = new Scanner(System.in);
System.out.println("I will calulate the service charge to cash your check");
System.out.print("Enter amount of check: $");
checkAmount = kb.nextDouble();
if (checkAmount > 0)
{
if (checkAmount <= 10)
{
fee = -1;
System.out.println("$1 service charge");
checkAmount = checkAmount + fee;
System.err.println("You have " + checkAmount + " left after service charge.");
}
else if ((checkAmount > 10) && (checkAmount <= 100))
{
System.out.println("There will be a 10 percent charge.");
fee = (checkAmount * .10);
checkAmount = checkAmount - fee;
System.out.printf("Processing fee: $%.2f\n" , fee);
System.out.printf("Check amount: $%.2f\n" , checkAmount);
}
else if ((checkAmount > 100) && (checkAmount <= 1000))
{
System.out.println("There will be a $5 charge plus 5 percent");
fee = ((checkAmount - 5) * .05);
checkAmount = (checkAmount - fee);
System.out.printf("Processing fee: $%.2f\n" , fee);
System.out.printf("Check amount: $%.2f\n", checkAmount);
}
else
{
System.out.println("$40 processing fee plus 1 percent");
fee = ((checkAmount - 40) * .01);
checkAmount = (checkAmount - fee);
System.out.printf("Processing fee: $%.2f\n" , fee);
System.out.printf("Check amount: $%.2f\n" , checkAmount);
}
System.out.println("Thanks for using Service Charger." + "\nGood bye");
}
}
}
For the last else statement, it seems a bit off from the rest of your statements. You're using "hold" to store the original checkAmount value, then modifying checkAmount to be the fee for the first three statements. You should model the last one like the one before it. The checkAmount should be checkAmount = (checkAmount * .01) + 40, then hold - checkAmount should return the value you're looking for. By having checkAmount = checkAmount - 40, the last line is returning hold (checkAmount) - (checkAmount - 40), which will always return 40.
System.out.println("$40 processing fee plus 1 percent");
fee = ((checkAmount - 40) * .01);
That's not a 40 dollar fee + 1 percent. That's a fee of slightly less than 1 percent; it's as if you cash out the first 40 dollars for free, and then apply a 1 percent charge to the rest.
Assuming the 1% charge applies to the whole check, rather than what's left after subtracting 40 dollars, the correct expression for the fee is
fee = 40 + 0.01*checkAmount;
Actually, you wanted to only charge the 1% fee over the check amount less the $40 dollar fixed fee according to your original expression, so the expression should be:
fee = 40 + (checkAmount - 40) * .01;
There's a lot of duplication in your code, which makes it harder to see what's going on, and if you decide to change - for example - the message that you want to show to the user, you now need to change it in 4 locations, and there's a big change that you forget to do it somewhere, or that you make a typo.
One of the goals of good programming is to avoid duplication as much as possible.
public class ServiceCharge {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("I will calulate the service charge to cash your check");
System.out.print("Enter amount of check: $");
double checkAmount = kb.nextDouble();
if (checkAmount > 0) {
double fee;
String feeMessage;
if (checkAmount <= 10) {
fee = 1;
feeMessage = "$1 service charge";
} else if ((checkAmount > 10) && (checkAmount <= 100)) {
feeMessage = "10 percent charge.";
fee = (checkAmount * .10);
} else if ((checkAmount > 100) && (checkAmount <= 1000)) {
feeMessage = "$5 charge plus 5 percent";
fee = 5 + ((checkAmount - 5) * .05);
} else {
feeMessage = "$40 processing fee plus 1 percent";
fee = 40 + ((checkAmount - 40) * .01);
}
checkAmount = checkAmount - fee;
System.out.printf("Fee structure: " + feeMessage);
System.out.printf("Processing fee: $%.2f\n", fee);
System.out.printf("Check amount: $%.2f\n", checkAmount);
System.out.println("Thanks for using Service Charger.\nGood bye");
}
}
}
The next step you may want to look into is to decompose your program functionally into functions. For example, the part where you ask for the amount, the part where you do the calculation, and the part where you show the result, are three very distinct parts. Each of those three you may want to change separately - you may want to get the input from a file or from a web request, and you may want to store use the result in another calculation rather than show it to the user.
So these could go into separate functions.
And then you could think about object decomposition - perhaps we're talking here about a CheckCashAction object that has properties for checkAmount, fee, feeStructure and payoutAmount.
Etc.
The nice thing then is that you can look at each of the steps separately and test them in isolation, which makes it easier to pinpoint bugs and to maintain the code.
Related
I am very new to java and have been stuck on a program that I've been trying to create. For background knowledge purposes, the program is for a company called "Ship It" which is a package shipping company. The user enters the weight of the package, and the distance it will travel. Depending on the weight, the company charges a fee per 200 miles.
0 < weight <= 3 pounds $1.00 charge
3 < weight <= 6 pounds $2.00 charge
6 < weight <= 10 pounds $3.00 charge
10 < weight <= 20 pounds $4.00 charge
20 < weight <= 30 pounds $5.00 charge
So far, this is the code I have:
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
//Variables
double costWithoutCharge = 0, weight, distance = 0;
//Introduction to ShipIt
System.out.print("\t\t******Welcome to ShipIt******\n");
System.out.print("***We are a low-charge, secure shipping company for packages" +
"up to 30 pounds***");
//User Enters Weight of Package
System.out.print("\n\nEnter the weight of the package (1.0 - 30.0 pounds): ");
weight = kb.nextDouble();
System.out.print("");
// User Enters distance the package will travel
System.out.print("Enter the miles to the destination (1 - 2000 miles): ");
distance = kb.nextInt();
System.out.print("");
//Weight If-else Statement
if (weight >30.0)
System.out.println ("\nSorry, you have entered invalid data - program terminated");
if (weight >30.0)
System.exit((int) weight);
//Distance Restriction if-else
if (distance >2000)
System.out.println ("\nSorry, you have entered invalid data - program terminated");
if (distance >2000)
System.exit((int) distance);
costWithoutCharge = distance / 200;
//If else
if (weight <0 || weight <=3)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*1.00);
}
else if (weight <3 || weight <= 6)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*2.00);
}
else if (weight <6 || weight <= 10)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*3.00);
}
else if (weight <10 || weight <= 20)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*4.00);
}
else {
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*5.00);
}
kb.close();
}
}
As of now, if I put a value like 1001, the cost to ship is $15.015, but it should be $18 since the charge is multiplied per 200 miles. I am on the fence if I need to do a new equation for the charge per 200 miles dilemma or if it can be supported with another if-statement?
I feel as though I have tried everything but I can't seem to solve this ): I am in dire need of help! Please!
The weight is missing from your example.
it sounds like in your example you have:
distance 1001
weight between 6 and 10, resulting in a $3 charge per "beginning 200 miles"
From your code, 15.015 gets returned.
It appears you want to calculate the "beginning 200 miles", so you could achieve that by rounding up:
costWithoutCharge = Math.ceil( distance / 200 );
On another note, you may want to remove the common parts from your if/then/else block. That is, only perform the calculation but not the System.out.println inside each clause.
First
if (weight <0 || weight <=3)
should be
if (0 < weight && weight <=3)
However the code should be easier to maintain, use a table of limits:
double[][] weightsAndCharges = {
{3, 1.00},
{6, 2.00},
{10, 3.00},
{20, 4.00},
{30, 5.00}
};
double charge = 10.00;
for (double[] weightAndCharge : weightAndCharges) {
if (weight <= weightAndCharge[0]) {
charge = weightAndCharge[1];
break;
}
}
System.out.printf("The cost to ship the package is: $%0.2f%n", charge*distanceRatio);
The answer is some basic math.
What you are thinking of is a combinatorial explosion: If you layer a whole batch of if/elseif statements inside each of your weight if statements for e.g. if (miles < 200) ... else if (miles >= 200 && miles < 400) - then think of it in dimensions: You have the 'miles' dimension which currently is adding 10 options (1-200, 200-399, 400-599, etc), the weight dimension which adds 5.
The amount of ifs you'd need here is then A*B: 50 ifs.
That's a ton, and clearly not what you want.
Math to the rescue!
You really just want to calculate costPerSegment * segments.
Calculate those 2 values individually, and now it's just A + B: 15 ifs. Given that you can actually use math itself to turn the miles number into the # of segments you need to charge (it's just division by 200 for the miles part, no lookup table involved), we're down to 5 ifs.
Note also your code is buggy. Your weight if statement have their > and < reversed. But the else if hides the problem. I fixed that problem in the snippet below.
double costPerSegment;
if (weight <=3) {
costPerSegment = 1.0;
} else if (weight <= 6) {
costPerSegment = 2.0;
} else if (weight <= 10) {
costPerSegment = 3.0;
} else if (weight <= 20) {
costPerSegment = 4.0;
} else {
costPerSegment = 5.0;
}
// Casting a positive double to an int automatically rounds down.
int segments = (int) miles / 200;
double cost = costPerSegment * segments;
This line is causing the problem for input distance 1001
costWithoutCharge = distance / 200; // result = 5,005
As far as I understood you want to have here just 5
So the simpliest solution would be to declare costWithoutCharge as int
and than
costWithoutCharge = (int) distance / 200; // result = 5
Or if you want to keep costWithoutCharge as double you can use Math lib to round it
costWithoutCharge = Math.round(distance / 200); // result = 5
This is the question: A store clerk wants a program that calculates the exact change to give a customer with the minimum number of bills and coins. You should input the amount of the purchase and the amount of money tendered (given to the clerk) and then output the change required and the number of each bill and coin to make up the change. Remember you want the minimum number of coins and bills in each case.
** Plan out this program first, before writing any code **
A sample run of the program is shown below.
Change Making Program
Please enter the total purchase: $1.42
Please enter the amount tendered: $20.00
The change will be: $18.58
To make up this amount you will need:
1 ten-dollar bill
1 five-dollar bill
1 two-dollar coin
1 loonie
2 quarters
1 nickel
3 pennies
Thank you for using the Change Making Program
This is what I have so far:
package defaultpackage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ChangeMaker {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the total of your purchase: $");
double total = Integer.parseInt(stdin.readLine());
System.out.print("Please enter the amount of money tendered: $");
double tendered = Integer.parseInt(stdin.readLine());
double change = tendered - total;
System.out.print("Your change is: $" +change);
if (change > 99.99)
{
double hundreds = (change - (change % 100)) / 100;
System.out.print("Hundred-dollar bills: " + hundreds);
change = change - (hundreds * 100);
}
if (change > 49.99)
{
double fifties = (change - (change % 50)) / 50;
System.out.print("Fifty-dollar bills: " + fifties);
change = change - (fifties * 50);
}
if (change > 19.99)
{
double twenties = (change - (change % 20)) / 20;
System.out.print("Twenty-dollar bills: " + twenties);
change = change - (twenties * 20);
}
if (change > 9.99)
{
double tens = (change - (change % 10)) / 10;
System.out.print("Ten-dollar bills: " + tens);
change = change - (tens * 10);
}
if (change > 4.99)
{
double fives = (change - (change % 5)) / 5;
System.out.print("Five-dollar bills: " + fives);
change = change - (fives * 5);
}
if (change > 1.99)
{
double toonies = (change - (change % 2)) / 2;
System.out.print("Toonies: " + toonies);
change = change - (toonies * 2);
}
if (change > 0.99)
{
double loonies = (change - (change % 1)) / 1;
System.out.print("Loonies: " + loonies);
change = change - (loonies * 1);
}
if (change > 0.24)
{
double quarters = (change - (change % 0.25)) / 0.25;
System.out.print("Quarters: " + quarters);
change = change - (quarters * 0.25);
}
if (change > 0.09)
{
double dimes = (change - (change % 0.1)) / 0.1;
System.out.print("Dimes: " + dimes);
change = change - (dimes * 0.1);
}
if (change > 0.04)
{
double nickles = (change - (change % 0.05)) / 0.05;
System.out.print("Nickles: " + nickles);
change = change - (nickles * 0.05);
}
if (change > 0)
{
double pennies = (change - (change % 0.1)) / 0.1;
System.out.print("Pennies : " + pennies);
change = change - (pennies * 0.1);
}
}
}
Here is a solution to the problem you present. It produces exactly the desired output.
The code uses integer math to avoid the precision problems you will inevitably have when using floating point values to represent dollar amounts. To do this, input values are multiplied by 100 and treated as cents. When printing out dollar amounts, we divide by 100 to represent the values in dollars.
Another feature of this code is that it is data-driven. Rather than duplicate the logic for removing each denomination over and over, a table provides the information about each denomination, and then there is only one block of code that is run in a loop to deal with each denomination. The code deals with properly pluralizing each denomination name when appropriate, including the special case for "pennies".
package defaultpackage;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.List;
class Denomination {
public Denomination(int value, String name, String pluralName) {
this.value = value;
this.name = name;
this.pluralName = pluralName;
}
public Denomination(int value, String name) {
this(value, name, null);
}
String getDescription(int count) {
String desc = this.name;
if (count > 1)
if (pluralName == null)
desc += 's';
else
desc = pluralName;
return desc;
}
public int getValue() {
return value;
}
private final int value;
private final String name;
private final String pluralName;
}
class ChangeMaker {
private static final List<Denomination> denominations = List.of(
new Denomination(10000, "one-hundred-dollar bill"),
new Denomination(5000, "fifty-dollar bill"),
new Denomination(2000, "twenty-dollar bill"),
new Denomination(1000, "ten-dollar bill"),
new Denomination(500, "five-dollar bill"),
new Denomination(200, "two-dollar coin"),
new Denomination(100, "loonie"),
new Denomination(25, "quarter"),
new Denomination(10, "dime"),
new Denomination(5, "nickel"),
new Denomination(1, "penny", "pennies")
);
public static void main(String[] args) throws IOException {
System.out.println("Change Making Program");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the total purchase: $");
int total = (int)(Double.parseDouble(stdin.readLine()) * 100);
System.out.print("Please enter the amount tendered: $");
int tendered = (int)(Double.parseDouble(stdin.readLine()) * 100);
int change = tendered - total;
System.out.printf("The change will be: $%.2f\n", change / 100.0);
System.out.println("To make up this amount you will need:");
for (Denomination denom: denominations) {
if (change == 0)
break;
if (change >= denom.getValue()) {
int count = change / denom.getValue();
if (count > 0) {
change = change - denom.getValue() * count;
System.out.printf("%d %s\n", count, denom.getDescription(count));
}
}
}
System.out.println("Thank you for using the Change Making Program");
}
}
Sample Run:
Change Making Program
Please enter the total purchase: $1.42
Please enter the amount tendered: $20.00
The change will be: $18.58
To make up this amount you will need:
1 ten-dollar bill
1 five-dollar bill
1 two-dollar coin
1 loonie
2 quarters
1 nickel
3 pennies
Thank you for using the Change Making Program
If the OP is asking this question to do a homework assignment, then I expect that this answer may be "too good". It may be using techniques not yet studied in class. Even if the OP could submit this as-is, I would encourage them to not do so. Instead, I'd suggest that they study this example, learn from it, and then incorporate what is learned into their own solution as appropriate. I encourage them to ask questions about the example, which I'd be happy to answer.
I have overseen the parseInt problem, but there is still another problem:
pennies = (change - (change % 0.1)) / 0.1;
...
change = change - (pennies * 0.1);
should be 0.01 instead of 0.1 - or just use what is left in change.
Advice: do not use double for money - lots of problems with rounding! (chances of change being short by one penny)
either use int/ long to represent cents, or
use BigDecimal
Note (change - (change % 100)) / 100 is basically the same as (int)(change / 100) - casting to int removes all decimals
I have a task here: Define a class PayPerView with method moviefee() that calculates the monthly charges for movies rented. The method should take one argument representing number of movies rented and return the fee as a double.
The rental fee fee is $6.99 per movie. Preferred customers that rent more than 10 per month get a discount of 5%.
Here's my code so far:
public class PayPerView {
public static void main(String [] args){
}
public static double moviefee(int n){
double fee = 6.99;
double total= n*fee;
System.out.println("Your balance due this month is" + total);
//return 6.99*n * ((n>10) ? 0.95:1);
}}
I know it's awful, I'm sorry and you can ignore that last line of code I commented out because I'm going to redo it and turn it into an if statement. I thought maybe I should use an array, but I can't right? Because I don't know how many movies are/will be rented? Should I use an arraylist for the number of movies rented?
Actually that line you commented out looks pretty much exactly what you are trying to do anyway. Is there something particularly wrong with it?
If you really need to output the result on the console...
final double fee = 6.99;
double total = n * fee * (n > 10 ? .95 : 1.0);
System.out.println("Your balance due this month is" + total);
return total;
I don't see why you'd use an ArrayList if you don't have any data to put into it.
You'd probably want to try something along these lines:
double total = n * fee;
if (n > 10) {
total *= 0.95;
}
I also see that you wanted to use the ternary operator, so you could replace the above code block with
double total = n * fee * (n > 10 ? 0.95 : 1.0);
Your on the right track
public static double moviefee(int n){
double fee = 6.99;
double total;
if(n <= 10){
total= n*fee;
}
else{
total= n*fee - (n*fee*0.05); //5 percent discount
}
System.out.println("Your balance due this month is" + total);
return total;
}
Edit: added double total;
Ok so i need to make a program to ask me for an amount of money, then I need it to tell me the least amount of coins to make it. The coins I can use are: dollars, quarters, dimes, nickels, and pennies. For example, When I run the program it's supposed to look like this:
> run Coins
Enter the amount of given money:
[1.73]
Give the seller 8 coins:
1 dollars,
2 quarters,
2 dime,
0 nickels,
3 pennies.
This is What I have so far:
import java.util.Scanner;
class Coins {
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
double money;
System.out.println("Enter the amount of money ");
money = input.nextDouble();
while (money > 0.0 ){
if (money >= 1) {
System.out.println(money/1+"dollars");
money -= 1;
}
else if (money>=.25) {
System.out.println(money/.25+"quarters");
money-=.25;
}
else if (money>=.10) {
System.out.println(money/.10+"Dimes");
money-=.10;
}
else if (money>=.05) {
System.out.println(money/.05+"Nickels");
money-=.05;
}
else if (money>=.01) {
System.out.println(money/.01+"Penny");
money-=.01;
}
}
}
}
The part I need help with is this: If I run the program and enter the amount 1.73, the way I have the code written, it takes the number 1.73, divides it by 1, and prints "1.73 dollars". I need a way to get rid of the decimal part so instead of printing "1.73 dollars", it prints "1 dollar". But I'm not sure how to do this. I tried converting it to an int but it messes up the flow of the other statements. Please help me.
You should use the combination of floor with casting to double, the following code works:
class Coins {
public static void main (String args[]) {
double money = 1.73;
while (money > 0.0 ){
if (money >= 1) {
System.out.println(Math.floor(money/1)+" dollars");
money -= Math.floor(money/1)*(double)1;
}
else if (money>=.25) {
System.out.println(Math.floor(money/.25)+" quarters");
money-=Math.floor(money/.25)*(double).25;
}
else if (money>=.10) {
System.out.println(Math.floor(money/.10)+" Dimes");
money-=Math.floor(money/.10)*(double).10;
}
else if (money>=.05) {
System.out.println(Math.floor(money/.05)+" Nickels");
money-=Math.floor(money/.05)*(double).05;
}
else if (money>=.01) {
System.out.println(Math.round(money/.01)+" Penny");
money-=Math.round(money/.01)*(double).01;
}
}
}
}
Another bug you had:
You should subtract Math.floor(money/XXX)*(double)XXX not (double)XXX
You need get rid of the remainder after the divisions. You can use Math.floor() for this:
class Coins {
public static void main (String args[]) {
double money = 1.73;
int dollars = (int) Math.floor(money/1);
money -= dollars * 1;
int quarters = (int) Math.floor(money/0.25);
money -= quarters * 0.25;
int dimes = (int) Math.floor(money/0.10);
money -= dimes * 0.10;
int nickels = (int) Math.floor(money/0.05);
money -= nickels * 0.05;
int pennies = (int) Math.round(money * 100);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
Resulting in:
Dollars: 1
Quarters: 2
Dimes: 2
Nickels: 0
Pennies: 3
I'm working on a program that will calculate the basic interest accrued on a certificate of deposit. The program asks for the amount of money invested and the term (up to five years). Depending on how many years their term is, is what determines how much interest is earned. I use an if/else statement to determine the rate of interest. I then use a loop to print out how much money is in the account at the end of each year. My problem is that when I run the program, the money is not counting.
Here is the entire code.
import java.util.Scanner;
public class CDCalc
{
public static void main(String args[])
{
int Count = 0;
double Rate = 0;
double Total = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you want to invest?");
int Invest = userInput.nextInt();
System.out.println("How many years will your term be?");
int Term = userInput.nextInt();
System.out.println("Investing: " + Invest);
System.out.println(" Term: " + Term);
if (Term <= 1)
{
Rate = .3;
}
else if (Term <= 2)
{
Rate = .45;
}
else if (Term <= 3)
{
Rate = .95;
}
else if (Term <= 4)
{
Rate = 1.5;
}
else if (Term <= 5)
{
Rate = 1.8;
}
int count = 1;
while(count <= 5)
{
Total = Invest + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}
}
}
and here is the result I get with a 10 dollar investment, just to keep it simple, and a 5 year investment.
How much money do you want to invest?
10
How many years will your term be?
5
Investing: 10
Term: 5
Value after year 1: 10.18
Value after year 2: 10.18
Value after year 3: 10.18
Value after year 4: 10.18
Value after year 5: 10.18
My main problem is I dont know how to make it continually add the intrest onto the total. I'm not sure if I need to use a different loop or what. Any help would be appreciated.
Total = Invest + (Invest * (Rate) / (100.0));
You are not changing the value of Invest for each year, so it is not compounding. It is like you are getting .18$ of interest each year, retired from the account.
Change Total for Invest.
You need to add the investment interest to your total:
Total = Invest;
int count = 1;
while(count <= 5)
{
Total = Total + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}