*3.33 (Financial: compare costs) 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. Here is a sample run:
Enter weight and price for package 1: 50 24.59
Enter weight and price for package 2: 25 11.99
Package 2 has a better price.
Enter weight and price for package 1: 50 25
Enter weight and price for package 2: 25 12.5
Two packages have the same price.
Enter weight and price for package 1: 50 24.59
Enter weight and price for package 2: 25 11.99
Package 2 has a better price.
Enter weight and price for package 1: 50 25
Enter weight and price for package 2: 25 12.5
Two packages have the same price.
import java.util.Scanner; public class ProgrammingEx3_33 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter weight and price for package 1:"); double w1 = input.nextDouble(); double p1 = input.nextDouble(); System.out.println("Enter weight and price for package 2:"); double w2 = input.nextDouble(); double p2 = input.nextDouble(); double r = w2 / p2 - w1 / p1; String s = ""; if (r < 0.0000001) { // comparing double to zero is not reliable, using // minimum threshold instead System.out.println("Two packages have the same price."); System.exit(0); } if (r > 0) { s = "Pakage 2"; } else { s = "Pakage 1"; } System.out.println(s + " has better price."); } }
No comments :
Post a Comment