I am supposed to write a program that computes the average grade of the student depending on the number of subjects to be entered.
Here’s my codes but it doesn’t execute in the part of entering grade on subject1:
import javax.swing.*;
public class Arrays {
static int ctr = 0;
public static void main(String[] args) {
String inputStr = "";
double num2process = 0.0;
double sum = 0.0, ave = 0.0;
double[] grade = new double[(int) num2process];
while (true) {
try {
inputStr = JOptionPane.showInputDialog(
"Enter number of subjects to enter: ");
num2process = Double.parseDouble(inputStr);
while (ctr < num2process) {
grade[ctr] = getNumber();
sum += grade[ctr];
ctr++;
}
} catch (NumberFormatException err) {
JOptionPane.showMessageDialog(
null,
"There is an error on entry",
"Error Message", JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
// Accumulate the output.
String output = "";
int ctr2 = 0;
output = "";
while (ctr2 > num2process) {
output += ("Grade on subject " + (ctr2+1)
+ " is " + grade[ctr]);
ctr2++;
}
ave = sum / num2process;
output += "\nAverage is " + ave;
// Display the output.
JOptionPane.showMessageDialog(
null,
output,
"The result is",
JOptionPane.INFORMATION_MESSAGE);
}
public static int getNumber() throws NumberFormatException {
String inputStr = "";
int num = 0;
try {
inputStr = JOptionPane.showInputDialog(
"Enter grade on subject " + (ctr+1));
num = Integer.parseInt(inputStr);
return num;
} catch (NumberFormatException errorAgain) {
throw errorAgain;
}
}
}
Please help me solve the error thanks
Your Code is throwing
ArrayIndexOutOfBoundExceptionbecause You are initializingdouble[] grade = new double[(int) num2process];before You get
num2process, So as you have initializeddouble num2process=0.0so it is taking
double[] grade = new double[0.0];So, You need to change it as follow (Initialize
gradeafter takingnum2process)Edit: As You Commented:
It’s supposed to display the grades of subject 1 to subject 3. the average is fine but how can i reduce it two decimal places only
Here’s the whole Program for You: