Question: / * * * @author Srimathi Vadivel * @author Sarah Benedicto * / public class FruitCosts { / * * * Main function to execute

/**
* @author Srimathi Vadivel
* @author Sarah Benedicto
*/
public class FruitCosts {
/**
* Main function to execute the program
*
* @param args command-line arguments, where args[0] is the file name to read from
*/
public static void main(String[] args){
// Do not remove this line, it opens the file for reading.
StdIn.setFile(args[0]);
// Reads amount of fruits from the input file
int numberOfFruits = StdIn.readInt();
// Creates parallel arrays for fruits and costs
String[] fruitNames = new String[numberOfFruits];
double[] fruitCosts = new double[numberOfFruits];
// Populate the arrays
for (int i =0; i < numberOfFruits; i++){
fruitNames[i]= StdIn.readString(); // Read fruit name
fruitCosts[i]= StdIn.readDouble(); // Read fruit cost
}
// Find 2 fruits with the lowest costs
int firstMinIndex =0;
int secondMinIndex =1;
// Ensure indices are correct
if (fruitCosts[1]< fruitCosts[0]){
firstMinIndex =1;
secondMinIndex =0;
}
// For loop in the array
for (int i =2; i < numberOfFruits; i++){
if (fruitCosts[i]< fruitCosts[firstMinIndex]){
secondMinIndex = firstMinIndex;
firstMinIndex = i;
} else if (fruitCosts[i]< fruitCosts[secondMinIndex]){
secondMinIndex = i;
}
}
// Output the fruit names and costs of 2 lowest
System.out.println(fruitNames[firstMinIndex]+""+ fruitCosts[firstMinIndex]);
System.out.println(fruitNames[secondMinIndex]+""+ fruitCosts[secondMinIndex]);
// Calculates and prints the total cost
double totalCost = fruitCosts[firstMinIndex]+ fruitCosts[secondMinIndex];
System.out.printf("Total %.2f
", totalCost);
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!