Saturday, June 21, 2014

Java Exercise Nr. 41 (Selections)

Suppose you shop for rice in two different packages. You would like to write a program to compare the cost. The program prompts the user to enter the weight and price of the each package and displays the one with the better price.

Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double weight1, price1, weight2, price2;
double ratio1, ratio2;

System.out.print("Enter weight and price for package 1:");
weight1 = s.nextDouble();
price1 = s.nextDouble();
ratio1 = weight1/price1;

System.out.print("Enter weight and price for package 2:");
weight2 = s.nextDouble();
price2 = s.nextDouble();
ratio2 = weight2/price2;

if(ratio1 < ratio2) {
System.out.print("Package 1 has better price.");
} else if(ratio1 == ratio2) {
System.out.print("Two packages have the same price.");
} else {
System.out.print("Package 2 has better price.");
}
}

1 comment:

  1. actually its ratio1 > ratio2 for package 1 having the better price.

    24/3=8 vs 12/2=6

    ReplyDelete

Author