Mean computation

• 02-21-2011, 07:01 PM
dienesh77
Mean computation
import javax.swing.JOptionPane;
public class ComputeMean {

/**
* @param args
* @return
*/
public static double main(String[] args) {
String mark = JOptionPane.showInputDialog("Enter Marks to calculate Mean:");
int marks = Integer.parseInt(mark);
double sum = 0;
int i = 0;
double average = 0;
while (marks != -1) {
sum = sum + marks;
average = sum / i;
i++;
return average;

}
if (marks == -1){

JOptionPane.showMessageDialog(null, "The average mark is "+average+"");

}
return average;
}

}

I made this code to compute the average of the marks that are input by the user. for some reason It wont run :/

could someone help me out please
• 02-21-2011, 07:05 PM
sunde887
Try using a scanner and an array, prompt for marks and fill the array with the inputs. From there you can use the array to very easily compute average with a loop.
• 02-21-2011, 07:11 PM
dienesh77
I haven't learned how to use arrays. Is it possible to do this without arrays?
• 02-21-2011, 07:17 PM
sunde887
it is, Do you know how to use a scanner? Your code is trying to do way too much. Simply get the mark, store it, convert it to an int with Integer.parseInt(). Then do sum += mark. Continue this process until you have collected all the marks you want. Once done, sum will be calculated, and you can easily compute average from there.

You may need a loop to prompt for the mark and add it to the sum.
• 02-21-2011, 07:18 PM
dienesh77
I do not know how to use scanner :/
• 02-21-2011, 07:25 PM
dienesh77
Is it possbile to like get the input for "marks", get it through the loop to compute sum and average and then clear off mark for the next input?
• 02-21-2011, 09:51 PM
sunde887
Yes you can reassign it. Try looking up the scanner api, it's easy to use. EAch step through the loop should get some input and add it to the sum.getting input reassigns mark
• 02-22-2011, 01:00 AM
Junky
The problem in the code you posted is that you ask for user input ONCE outside the loop. Simply move that inside the loop.