Search code examples
javadecimalformatsystem.in

Trying to Understand Where My Loop Goes Wrong


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?


Solution

  • 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.