The goal of this la b is to write a program for computing the fuel economy for a number of cars and producing the best and the second cars of all the cars entered. The program first asks the user to enter the number of cars to consider and then the user enters the number. The program then executes a for-loop with which to collect information of the individual cars. The program remembers the best and the second best cars in terms of their make, model, and mpg. Each time the new car information is entered, the program checks whether the new car is better than either of the best or the second best, and if so, makes some update so that the best and the second best so far are correctly identified. The best and the second best ones are recorded using variables make1st , model1st , mpg1st , make2nd , model2nd , and mpg1st , mpg2nd . While the input by the user is directly used for the make and the model, the mpg is calculated from three quantities the user enters. The three quantities are the start odometer read (in miles), the end odometer read (in miles), and the gas consumed (in gallons). The mpg value is the difference between the two odometer reads divided by the gas consumed. So that the updating operation is the saame regardless of how many cars have been entererd so far, we can initialize mpg1st and mpg2nd with the value of 0.
Suppose nCars is an int variable that holds the number of cars for which the user is to enter the information for. A natural way to write the code for information gathering and for updating the 1st and 2st bests is to use the following code structure:
The part (c) and (d) will together constitute an if-else-if block. If neither is the case, nothing will happen; the new car will be removed from consideration for the 1st or the 2nd best.
It is possible to make this for-loop more fanciful by asking user to whether to accept the information that has just been entered, since the user may have mistyped the information. We can envision that the user enters a response and whose first letter will be the indication of whether to accept or not (the first letter being ‘n%rsquo; will be interpreted as a no; to simplify, any other response will be interpreted as a yes).
So, if the user enters a string starting with a the String literal “n’, we want to go back to the same value of i, instead of going to the next value of i. How can we do this? The answer is to use an integer variable, which we will call "advance" to determine how much to add to i and change the update part of the for-loop to i += advance. Inside the loop body, we initialize the value of advance to 1. Then if the answer is a "no", we change it to 0. The variable advance must be defined outside the for-loop. So, the code will look like:
To produce information on screen, you can use printf for formatting.
Here is a sample execution of the code:
You may use this template: FuelEconomy.java