162k views
5 votes
Write a program that can compare the unit (per lb) cost of sugar sold in packages with different weights and prices. The program prompts the user to enter the weight and price of package 1, then does the same for package 2, and displays the results to indicate sugar in which package has a better price. It is assumed that the weight of all packages is measured in lb. The program should check to be sure that both the inputs of weight and price are both positive values.

1 Answer

0 votes

Answer:

// program in java.

// package

import java.util.*;

// class definition

class Main

{

// main method of the class

public static void main (String[] args) throws java.lang.Exception

{

try{

// scanner Object to read the input

Scanner sc = new Scanner(System.in);

System.out.print("Enter Package1 Weight:");

// read the Weight of Package1

double w1 = sc.nextDouble();

// check weight is negative or not

while (w1 < 0)

{

System.out.print("weight can't be negative. Enter again:");

// read again

w1 = sc.nextDouble();

}

System.out.print("Enter Package1 Price:");

// read the Price of Package1

double p1 = sc.nextDouble();

// check price is negative or not

while (p1 < 0)

{

System.out.print("price can't be negative. Enter again:");

// read again

p1 = sc.nextDouble();

}

System.out.print("Enter Package2 Weight:");

// read the Weight of Package1

double w2 = sc.nextDouble();

// check weight is negative or not

while (w2 < 0)

{

System.out.print("weight can't be negative. Enter again:");

// read again

w2 = sc.nextDouble();

}

System.out.println("Enter Package1 Price:");

// read the Price of Package2

double p2 = sc.nextDouble();

// check price is negative or not

while (p2 < 0)

{

System.out.print("price can't be negative. Enter again:");

// read again

p2 = sc.nextDouble();

}

// check better price

if (w1 / p1 > w2 / p2)

System.out.println("package1 has better price");

else

System.out.println("package2 has better price");

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Read the weight of package1 and if weight is negative then ask again to enter the weight.Read price of package1 and if price is negative then again ask to enter price. Similarly read weight and price for package2.Then find weight1/price is greater then package 1 has better price else package2 has better price.

Output:

Enter Package1 Weight:-2

weight can't be negative. Enter again:5

Enter Package1 Price:-100

price can't be negative. Enter again:120

Enter Package2 Weight:-4

weight can't be negative. Enter again:4

Enter Package1 Price:-100

price can't be negative. Enter again:100

package1 has better price

User Cachapa
by
5.2k points