Trying to Understand Where My Loop Goes Wrong - java

So here is my task:
A postal company for a package charges $15 for the first
pound or a fraction thereof and $10 per pound for anything over one
pound. Write a program that prints the charge of a package.
Variables:
weight
First execution:
Weight? -12 Weight must be a positive number.
Second Execution:
Weight? 0 Weight must be a positive number.
Third Execution:
Weight? 2 Pay: $25.00
Forth Execution:
Weight? 2.8 Pay: $33.00
Fifth Execution:
Weight? 2.07 Pay: $25.70
and Here is the code I have developed so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
for (double i = 1; i < weight; i = i + .01) {
if (weight > 1) {
output = output + (1 / 10.00);
}
}
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
Everything works, but what I can't figure out is why (especially in the Fourth and Fifth Execution) is the final output always .10 cents off. Can anyone help me get to the accuracy I need?

Here is what I came up with:
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else {
// Print the charge of the package
if (weight > 1) {
output = cost + ((weight-1) * 10);
} else {
output = cost;
}
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
This should handle all of your cases, as well as numbers between 0 and 1 assuming it's $1 per 0.1 lbs. Instead of your for-loop, you can just use the cost + ((weight-1) * 10) formula. I removed the check to see if weight was equal to 1 because it's handled in the else clause.

If I understand the question correctly, you should never have any fractional dollar amount because anything over a pound is automatically rounded up to the next pound. ie: 2.01 lbs would become 3 lbs. If this is correct, then you could use Math's ceil function to round the weight up to the nearest whole pound, then do something like this:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
double temp = (Math.ceil(weight)) - 1;
for(double i = temp; i > 0; i-- ) {
output += 10;
}
output += cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
This way, you don't need to bother with 10 cent increments. I hope this helps. Let me know if you have any questions.

This: double i = 1; i < weight; i = i + .01 could be your problem.
Doubles are not exact for decimal math. You're expecting i == weight, at which point the loop should stop, but it might not because i + .01 (however many times) is a tiny fraction less than weight.
My advice is to ditch the loop. If the package is over 1 lb, just subtract one pound from the weight, multiply by the $10 per pound, and then round to the two decimal places you need (NOTE: round it according to how it's spec'd to be rounded, don't just let the conversion from double to decimal do it on its own. There are multiple ways to round something, and decimal does not magically know which one is right for your problem.)
EDIT: Look at your solution, is it supposed to only work to a resolution of 1/10 of a lb? If so, start by rounding the weight. Again, round it according to how it needs to be rounded (down, up, or nearest).

Related

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Nickles in Coin Counter not displaying correct amount

I was just given my first assignment in my Java class, and we were tasked with creating a program that counts nickles and displays the total amount of money. However, whenever I put an odd number of nickles it does not display the corrent amount of money. For example, 1 nickles turns into $.5 instead of $.05. 21 Nickles turns into $1.5 instead of $1.05. I'm asumming this is an easy fix for an easy problem, but I am finding myself stumped. Thanks for the help.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
int nickles5 = nickles * 5;
int dollars = nickles5 / 100;
int change = nickles5 % 100;
System.out.println("You have $" + dollars + "." + change);
}
I'll go out on a limb here, to try to solve your problem. It appears that you will ask the user to enter some number of nickels, and you will output the amount in dollars. Please let me know if this is incorrect in any way.
Now look at the following code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
double nickles5 = nickles * 0.05;
System.out.println("You have $" + nickles5);
}
After we have the number of nickels stored in an int, we multiply it by 0.05, to get the actual value of all the nickels. We store this in a double variable [Note: int multiplied to a double, returns a double; it is called numeric promotion]. Now, to get the total value, you can simply print this double variable. In a case where n=2, nickels5 = 0.1. So, it will print $0.1
If you want this to show up as $0.10, simply replace the nickels5 with String.format( "%.2f", nickels5)
Now your final line will look like:
System.out.println("You have $" + String.format( "%.2f", nickels5));
Let me know if this solved your issue.
You need to format change to use 2 digits, rather than just printing out the raw number. Specifically, if change==5, you want to print out 05.
You can do this with String.format("%02d", change)
You have a random apostrophe at the end, why?
You want to use floats instead of ints, like this:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
System.out.println("$"+ amount);
Output:
Deposit your Nickles.
1
$0.05
Deposit your Nickles.
21
$1.05
EDIT: Code with formatted output:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
String output = String.format("%02f", amount);//f(loat) not d
System.out.println("$"+ output);

My 'if' statement is not working properly

I have an assignment where I am supposed to determine whether the average of three values is 'above average' or 'below average'. For some reason whatever is input will always be above average as the result. Here is my code below, thank you for any help!
import java.util.Scanner;
class Lesson_12_Activity_One {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter three values");
double x = scan.nextDouble();
double y = scan.nextDouble();
double z = scan.nextDouble();
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
}
The average is t/100 but in your condition you test if t > 89.5 (which is always true since t is the average multiplied by 100).
Just remove both the multiplication by 100 and the division by 100. They don't seem necessary.
double t = Math.round((x+y+z)/3);
System.out.print("The average is " + t);
if(t >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
}
if(t/100 >= 89.5)
System.out.print(" ABOVE AVERAGE");
else
System.out.print(" BELOW AVERAGE");
by the way why are you multiplying and then dividing by 100?
I'm gonna guess that you're mixing up perunages and percentages. That means, at one point in your program you use 0.5 and in the other 50, both as 50%.
double t = (double)Math.round(100*((x+y+z)/3));
System.out.print("The average is " + (t/100));
With x, y and z all as 50, this will output 50. t = 100 * (50 + 50 + 50)/3 = 5000, the output is (t/100) = 50.
if(t >= 89.5) however tests with t = 5000.
To solve this, go down one of two paths.
Replace all percentages for perunages. This means inputting numbers from 0 to 1.
To do this, do the following:
change your t-initialization for double t = (double)Math.round(1000*((x+y+z)/3)) / 1000 This will make T be in between 0 and 1 with 3 digits precision.
Replace your if with if (t >= 0.895)
Replace all perunages with percentages. This means inputting numbers from 0 to 100.
To do this, remove the 100* from your double t = (double)Math.round(100*((x+y+z)/3));, and the /100 from the output message.

Java: How to infinitely enter numbers, stop when negative number is entered and computer the average

I am trying to write a Java program that takes in a potentially infinite number of values - and once the user enters a negative number, the program stops, computes the average of all of the entered numbers (excluding the negative one) and prints out how many numbers were entered (once again, not the negative one) as well as the average.
Below is the code I currently have. When I try to run the program, it does not computer the average correctly and you have to enter a couple consecutive negative numbers for it to finally stop the program.
To test the arithmetic and the rest of the program, I inserted a statement that would close the program if the word "negative" was entered rather than a negative number. When did this, the average and count and everything else worked just like it was made to. Essentially, the problems start to occur when I try to stop the program after a negative number.
I am a beginning programmer and this has been driving me crazy for a couple hours. Any help is greatly appreciated!
import java.util.*;
import java.lang.Math;
import java.io.IOException;
import java.io.InputStream;
public class Average
{
public static void main(String[] args)
{
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += numInput.nextDouble();
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
}
You should use: sum+=negNum; instead of sum += numInput.nextDouble();
As it is now, your program, reads a number and if it is not negative it reads another number and adds it to the sum.
Also, you should compute the average only once in the else block.
You are reading a new number to compute the sum.
It should be
sum += negNum;
You have already received the number entered by the user in line:
double negNum = numInput.nextDouble();
You should add this number itself to sum rather than asking for another number from user by calling numInput.nextDouble() again. So the fixed code would be:
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum >= 0)
{
sum += negNum;
count++;
avg = sum/count;
}
else
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
}
}
Sample Run:
Enter a series of numbers. Enter a negative number to quit.
2
3
-1
You entered 2.0 numbers averaging 2.5.
Change
sum += numInput.nextDouble(); // reading next value again
to
sum += negNum;

My Java program is outputting the wrong answer when finding tax for a salary

There is no tax on the first 20% of salary entered. i.e for 20000..it would tax for 16000 with 10% on 15000 and 20% on the remaining 1000 which would be 1700 total tax. My program incorrectly outputs 14500....
import java.util.*;
public class taxable {
public static void main (String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter your salary:");
double salary=in.nextDouble();
double taxDue=0;
double tempTaxDue=0;
if (salary < 15000) {
System.out.println("No tax applicable");
}else if
(salary >=15000 && salary <20000) {
taxDue=(15000*0.1);
}else if
(salary >=20000 && salary <=35000) {
tempTaxDue=(salary*0.8);
taxDue=15000*0.1+tempTaxDue-15000*0.2;
}else if
(salary > 35000) {
tempTaxDue=salary*0.8;
taxDue=(15000*0.1)+(20000*0.2)+(tempTaxDue-35000*0.35);
taxDue=(salary*0.8)+(20000*0.2)+(salary-35000*0.35);
}
System.out.printf("The amount of tax due is: " + taxDue + " ");
double avTaxRate;
avTaxRate=taxDue/salary*100;
System.out.printf("The average tax rate: " + avTaxRate + "%%");
}
}
When dividing integer values, always check for floating point division - 10/100 will be 0 by Java integer division terms, 10.0/100 circumcises this.
To get 10% out of something either divide it by 10.0 or multiply by 0.1.
taxDue = 15000 * 0.1;
But the biggest hidden problem here is you shouldn't use double to represent money. Use BigDecimal instead.
Why? Just for fun, let's calculate the 10% taxes over 15001?
double dValue = 15001;
double dTaxes = 15001 * 0.1;
System.out.println("Taxes with double: " + dTaxes);
// Taxes with double: 1500.1000000000001
Precision error -> Small, but it is there 0.0000000000001.
BigDecimal to the rescue:
BigDecimal value = new BigDecimal("15001");
BigDecimal taxes = value.multiply(new BigDecimal("0.1"));
System.out.println("Taxes with BigDecimal: " + taxes);
// Taxes with BigDecimal: 1500.1
Working example.
You have to use casting when you trying to assign to double variable some division, instead:
taxDue=15000*(10/100);
smt as make one of divisor double value:
taxDue = 15000.0 * (10.0 / 100);

Categories

Resources