In: Computer Science
A shipping company uses the following function to calculate the cost (in dollars) of shipping based on the weight of the package in pounds:
Weight | Cost |
---|---|
0 < w <= 1 | 3.5 |
1 < w <= 3 | 5.5 |
3 < w <= 10 | 8.5 |
10 < w <= 20 | 10.5 |
Your program, named Shipping.java should ask for the weight of the package and display the shipping cost. If the weight is negative or zero, display a message “Invalid input.” If the weight is greater than 20, display a message “The package cannot be shipped.”
Here is an example of the output of the program. Your output does not have to look exactly like this, but it must reflect the same information. User input is shown in bold.
Enter weight of package in pounds: 5.7 Cost: $8.50 Enter weight of package in pounds: 25.2 The package cannot be shipped.
What I did:
import java.util.Scanner;
public class Shipping
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter weight of package in pounds"+" ");
double weight = input.nextDouble();
double cost;
if(weight<=1&&weight>0)
{
cost=3.5;
System.out.println("Cost:"+" "+"$"+cost);
}
else if(weight<=3&&weight>1)
{
cost=5.5;
System.out.println("Cost:"+" "+"$"+cost);
}
else if(weight<=10&&weight>3)
{
cost =8.5;
System.out.println("Cost:"+" "+"$"+cost);
}
else if(weight<=20&&weight>10)
{
cost=10.5;
System.out.println("Cost:"+" "+"$"+cost);
}
else if(weight==0||weight<0)
{
System.out.println( "Invalid input.");
}
else
{
System.out.println( "The package cannot be shipped.");
}
}
}
Is this correct?
Yes, It is absolutely correct as it is giving good results for every possbile inputs.
Sample run screenshots: