It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming Java Forum

PLeaSE help me on this ForLoop Java Program.

PLeaSE help me on this ForLoop Java Program.

Postby kdreamx on Thu Apr 05, 2007 7:19 pm

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 (4 for asking gender and 4 for asking GPA). I can't figure out why...
Also, i have to change this to For Loop...

Can anyone help me on this???
======================================================
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);

}
}
kdreamx
 
Posts: 2
Joined: Mon Mar 19, 2007 8:56 pm

my answer to your problem

Postby ggomez on Tue Apr 17, 2007 5:11 am

if you put the JOptionPane.... inside the while loop, you will open it the 4 times but they are still defining the same variable, so you will only work with the las time you do the input.

i´d recommend something like this
Code: Select all

String[] i=new String[MAX];

for(int x=0;x<MAX;x++)
{
   i[x]=JOptionPane.showInputDialog......
}



then you will have an array with the inputs.
ggomez
 
Posts: 45
Joined: Tue Apr 17, 2007 3:30 am
Location: !!!!!MéXiCo¡¡¡¡¡¡


Who is online

Users browsing this forum: No registered users and 0 guests