I am creating a calculator to calculate shipping costs. The code goes something like this:
class ShippingCalc {
public static void main(String[] args) {
int weight = 30;
if (weight < 10) {
System.out.println("Shipping costs $1.");
}
else if (weight < 20) {
System.out.println("Shipping costs $2.");
}
else {
System.out.println("Shipping costs $3.");
}
}
}
This is all great but I want to create a calculator that can calculate based on already set values. For example, something that says:
if (weight < 250) {
// print("Shipping cost is $1);
} else if (weight < 499) {
// print("Shipping cost is $2);
} else if (weight < 749) {
// print...etc and it keeps going
This will be based on user input that is why I don’t want to already have any constraints like above. Is it possible to make such a calculator in Java that no matter how much the weight, it calculates the shipping costs appropriately and gives out the answer.
If yes, then how do I go about it?
First, you need a formula or table for calculating the shipping costs. For example, “the shipping is one dollar per whole ten pounds of weight”.
Then, you put the weight into that formula.
If you want the formula to be more complex, you can do something like this:
Where the users can define the value of the
threshold1andthreshold2variables.There can be an unbounded number of these levels:
Welcome to the wonderful world of computer programming!