-
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
-
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.
-
I haven't learned how to use arrays. Is it possible to do this without arrays?
-
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.
-
I do not know how to use scanner :/
-
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?
-
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
-
The problem in the code you posted is that you ask for user input ONCE outside the loop. Simply move that inside the loop.