Issue
I have a problem. I am tasked to write a Java program, using the array method, that receives the marks of 5 students, and then finds and displays the number of students getting A grade. The marks are (60,56,78,99,92.5). The criteria needed to get grade A is 80 marks and above.
Everything in my code went well, except for the last statement: System.out.println("The number of students "+count);
This is my code:
import javax.swing.JOptionPane;
public class Q2 {
public static void main(String [] args) {
double[] marks = new double[6];
int numbers = 1;
// This is for asking input
for (int i = 0; i < marks.length; i++,numbers++) {
String marksString = JOptionPane.showInputDialog (null,
"Enter the marks for student "+numbers+": ");
marks[i] = Double.parseDouble(marksString);
int count = 0;
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students "+count);
}
}
Everything in my code went well, except for the last statement: System.out.println("The number of students "+count);
I received an error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type:
Is there anyone who can explain and correct my mistakes? :D
Solution
You wrongly declared count
inside the for
loop. As a result, it is not accessible outside the loop (hence the compilation error), and in addition, it's overwritten to 0 in each iteration of the loop, which means it will always have a value of 0 or 1 (before exiting the loop), instead of the correct count.
Move it outside the loop:
double[] marks = new double[6];
int numbers = 1;
int count = 0;
// This is for asking input
for (int i = 0; i < marks.length; i++,numbers++) {
String marksString = JOptionPane.showInputDialog (null,
"Enter the marks for student "+numbers+": ");
marks[i] = Double.parseDouble(marksString);
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students who got A is " + count);
Answered By - Eran
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)