Results 1 to 2 of 2
Thread: Help with ForLoop
- 07-05-2007, 06:16 AM #1
Senior Member
- Join Date
- Jun 2007
- Posts
- 114
- Rep Power
- 0
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...
Can anyone help me on this???ThanksJava 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); } }
Albert:rolleyes:
- 07-05-2007, 06:24 AM #2
Member
- Join Date
- Jun 2007
- Posts
- 92
- Rep Power
- 0
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
So, we have an initial condition, where you can initialize a variable if you'd like.Java Code:for( initial_condition ; boolean_expression ; ending_expression) // body
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
output:Java Code:for(int i = 1; i <= 10; i++) { System.out.println(i); }
We have an initial condition where we initalize i to 1; (int i = 0)Java Code:1 2 3 4 5 6 7 8 9 10
We have a boolean test (i <= 10)
And we have an ending condition to increment the number i (i++)
An equivalent while loop:
GreetingsJava Code:int i = 1; while(i <= 10) { System.out.println(i) i++; }
Marcus:cool:


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks