-
Help with ForLoop
I have to write a program that prompts the user to input the gender and GPA of four students, and print the average GPA for both male and female students when the loop ends.
I was able to compile and run, but uh...it doesn't work the way it should.
The dialog box pops up more than 8 times
Also, i have to change this to For Loop...
Code:
import javax.swing.*;
public class Loop1
{
public static void main(String [] args)
{
String gender, male, female;
double gpa;
double maleTotal;
int maleCounter;
double femaleTotal;
int femaleCounter;
double maleGpa;
double femaleGpa;
String input1, input2;
final int MAX = 4;
int i;
maleTotal = 0;
femaleTotal = 0;
maleCounter = 0;
femaleCounter = 0;
i = 0;
input1 = JOptionPane.showInputDialog(null, "Enter Gender: male or female");
while (i < MAX)
{
if(input1.equals( "male" ))
{
input2 = JOptionPane.showInputDialog(null, "Enter GPA:");
gpa = Double.parseDouble(input2);
maleTotal = maleTotal + gpa;
maleCounter++;
}
else if(input1.equals( "female" ))
{
input2 = JOptionPane.showInputDialog(null, "Enter GPA:");
gpa = Double.parseDouble(input2);
femaleTotal = femaleTotal + gpa;
femaleCounter++;
}
input1 = JOptionPane.showInputDialog(null, "Enter Gender: male or female");
i++;
}
if(maleCounter != 0 && femaleCounter != 0)
{
maleGpa = (double)maleTotal/maleCounter;
femaleGpa = (double)femaleTotal/femaleCounter;
JOptionPane.showMessageDialog(null, "Average Male GPA is:" + maleGpa+"\nAverage Female GPA is:" + femaleGpa);
}
System.exit(0);
}
}
Can anyone help me on this???Thanks
Albert:rolleyes:
-
Well let me explain what a for loop is.
A for loop is much like a while loop. In fact a for loop can be used as a while loop given a certain scenario, but we will get to that later.
All for loops have the following format
Code:
for( initial_condition ; boolean_expression ; ending_expression)
// body
So, we have an initial condition, where you can initialize a variable if you'd like.
Then a boolean expression that tests a condition if it's true or false. If it's true then it goes into the body of the loop.
At the end of the body the ending_expression is then called in the for loop, and we evaluate the boolean expression all over again.
So for example, if I wanted to count to ten from 1
Code:
for(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
output:
Code:
1
2
3
4
5
6
7
8
9
10
We have an initial condition where we initalize i to 1; (int i = 0)
We have a boolean test (i <= 10)
And we have an ending condition to increment the number i (i++)
An equivalent while loop:
Code:
int i = 1;
while(i <= 10)
{
System.out.println(i)
i++;
}
Greetings
Marcus:cool: