Pages

Tuesday, 7 June 2016

Chapter 3 Exercise 18, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*3.18 (Cost of shipping) A shipping company uses the following function to calcu-
late the cost (in dollars) of shipping based on the weight of the package (in
pounds).

c(w)=3.5, if 0  <w< = 1
c(w)=5.5, if 1 <w < = 3
c(w)=8.5, if 3 <w< = 10
c(w)=10.5, if 10<w< = 20

Write a program that prompts the user to enter the weight of the package and display the shipping cost. If the weight is greater than 50, display a message “the package cannot be shipped.


import java.util.Scanner;
 
public class ProgrammingEx3_18 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter the weight of the package in pound:");
  double w = input.nextDouble();
  double cost = 0;
 
  if (w > 0 && w <= 1) {
   cost = 3.5;
  } else if (w > 1 && w <= 3) {
   cost = 5.5;
  } else if (w > 3 && w <= 10) {
   cost = 8.5;
  } else if (w > 10 && w <= 20) {
   cost = 10.5;
  }
 
  if (cost == 0) {
   System.out.print("the pakage cannot be shipped.");
   System.exit(0);
  }
 
  System.out.print("The cost of shipping is " + cost);
 
 }
 
}

No comments:

Post a Comment