The problem Suppose you shop for rice in two different packages. You would like to write a program to compare the cost. In this examples , write a program prompt the user to enter the weight and price of the each package and displays the one with the better price.
Breaking it down public static void main ( String [] strings ) {
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter weight and price for package 1: " );
double weight1 = input . nextDouble ();
double price1 = input . nextDouble ();
System . out . print ( "Enter weight and price for package 2: " );
double weight2 = input . nextDouble ();
double price2 = input . nextDouble ();
input . close ();
if ( calculateBetterPrice ( weight1 , price1 , weight2 , price2 )) {
System . out . println ( "Package 1 has a better price." );
} else {
System . out . println ( "Package 2 has a better price." );
}
}
private static boolean calculateBetterPrice ( double weight1 , double price1 ,
double weight2 , double price2 ) {
return price1 * 1.0 D / weight1 >= price2 * 1.0 D / weight2 ;
}
Output Enter weight and price for package 1: 50 24.59
Enter weight and price for package 2: 25 11.99
Package 1 has a better price.
Financial compare costs posted by Justin Musgrove on 09 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch3
Share on: Facebook Google+