The program I am writing is one that has a validation loop to see if a family has the right amount of members for a survey (3-6) about their househould mpg. If they don't i have the program setup to tell them the do no meet the requirements and must enter a different number if they would like to proceed. I understand the validation loop i think, but the next part of the for
loop is not as easy.
I'm not sure how the program will know how many times the user should enter the different mpgs for each car in the family. For instance if one family has 3 members and the other has 5. I need a separate input box. I'm mostly confused on what i would put in the for argument. Here is my code that I have so far.
EDIT: I have what I think is the correct way to format the for loop. Now I have to figure out how to have the user input the data into the body of the for loop. So if they have 3 cars I need to have them enter the mpg for each and then calculate the average. Im stuck on how to store each cars mpgs separately.
import javax.swing.JOptionPane;
public class MpgRetry
{
public static void main(String[] args)
{
String familyMembersStr, mpgStr;
int familyMembers;
int mpgAverage;
familyMembersStr = JOptionPane.showInputDialog("Please enter number of family members: ");
familyMembers=Integer.parseInt(familyMembersStr);
while(familyMembers <3 || familyMembers >6)
{
JOptionPane.showMessageDialog(null, "Sorry, this survey can only use data from families with 3-6 members.");
familyMembersStr = JOptionPane.showInputDialog("Please enter the number of family members (3-6): ");
familyMembers = Integer.parseInt(familyMembersStr);
}
double[] mpg = new double[familyMembers]; // creat array to hold values
for (int i = 0; i < familyMembers; i++)
{ // assuming each member has one car
mpgStr = JOptionPane.showInputDialog("Please enter MPG each car (separately): ");
mpg[i] = Integer.parseInt(mpgStr);
}
mpgAverage = (mpg / familyMembers);
JOptionPane.showMessageDialog(null,"The average mpg of this family is " + mpgAverage + ".");
}
}