208k views
4 votes
The Fast Freight Shipping Company charges the following rates for different package weights:

2 pounds or less: $1.50
over 2 pounds but not more than 6 pounds: $3.00
over 6 pounds but not more than 10 pounds: $4.00
over 10 pounds: $4.75
Write a program that asks the user to enter the weight of a package and then displays the shipping charges. The program should also do "Input Validation" that only takes positive input values and show a message "invalid input value!" otherwise.

1 Answer

5 votes

Answer:

import java.util.Scanner;

public class ShippingCharge

{

static double wt_2=1.50;

static double wt_6=3;

static double wt_10=4;

static double wt_more=4.75;

static double charge;

static double weight;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

do

{

System.out.print("Enter the weight of the package: ");

weight = sc.nextDouble();

if(weight<=0)

System.out.println("Invalid input value!");

}while(weight<=0);

if(weight<=2)

charge=wt_2;

else if(weight<=6 && weight>2)

charge=wt_6;

else if(weight<=10 && weight>6)

charge=wt_10;

else

charge=wt_more;

System.out.println("Shipping charges for the entered weight are $"+charge);

}

}

OUTPUT

Enter the weight of the package: 0

Invalid input value!

Enter the weight of the package: 4

Shipping charges for the entered weight are $3.0

Step-by-step explanation:

1. The variables to hold all the shipping charges are declared as double and initialized.

static double wt_2=1.50;

static double wt_6=3;

static double wt_10=4;

static double wt_more=4.75;

2. The variable to hold the user input is declared as double.

static double charge;

static double weight;

3. The variable to hold the final shipping charge is also declared as double.

4. Inside main(), an object of Scanner class is created. This is not declared static since declared inside a static method, main().

Scanner sc = new Scanner(System.in);

5. Inside do-while loop, user input is taken until a valid value is entered.

6. Outside the loop, the final shipping charge is computed using multiple if-else statements.

7. The final shipping charge is then displayed to the user.

8. All the code is written inside class since java is a purely object-oriented language.

9. The object of the class is not created since only a single class is involved.

10. The class having the main() method is declared public.

11. The program is saved with the same name as that of the class having the main() method.

12. The program will be saved as ShippingCharge.java.

13. All the variables are declared as static since they are declared outside main(), at the class level.

User EliuX
by
6.7k points