帮助Java代码,获得5名学生的分数,并显示获得using Arrays方法的学生
我有个问题。我的任务是使用数组方法编写一个Java程序,该程序接收5名学生的分数,然后查找并显示获得分数的学生人数。分数为60,56,78,99,92.5。获得A级的标准是80分及以上 我的代码中的一切都很顺利,除了最后一句话: System.out.println学生人数+计数 这是我的代码:帮助Java代码,获得5名学生的分数,并显示获得using Arrays方法的学生,java,arrays,netbeans,runtimeexception,Java,Arrays,Netbeans,Runtimeexception,我有个问题。我的任务是使用数组方法编写一个Java程序,该程序接收5名学生的分数,然后查找并显示获得分数的学生人数。分数为60,56,78,99,92.5。获得A级的标准是80分及以上 我的代码中的一切都很顺利,除了最后一句话: System.out.println学生人数+计数 这是我的代码: import javax.swing.JOptionPane; public class Q2 { public static void main(String [] args) { d
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);
}
}
我的代码中的一切都很顺利,除了最后一句话:
System.out.println学生人数+计数
我收到一个错误:
线程主java.lang.RuntimeException中的异常:不可编译
源代码-错误的树类型:
有人能解释和纠正我的错误吗D您在for循环中错误地声明了count。因此,它在循环外部不可访问,因此会出现编译错误,此外,在循环的每次迭代中,它都会被覆盖为0,这意味着在退出循环之前,它将始终具有0或1的值,而不是正确的计数
将其移出循环:
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);
您的错误是您在循环中初始化了计数,并且在每次迭代中,编译器都将值0分配给您的计数。将其置于循环上方。您已经在循环内声明并初始化了count变量。因此,您将无法访问for循环外的count变量。每次循环进行时,count变量都将分配给0。这是您已执行的两个错误
import javax.swing.JOptionPane;
public class Demo {
public static void main(String [] args) {
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);
//int count = 0;
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students "+count);
}
}
您应该在for循环之外声明count变量。的可能重复也可能重复:学生数+计数->获得:+计数的学生数。。。
import javax.swing.JOptionPane;
public class Demo {
public static void main(String [] args) {
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);
//int count = 0;
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students "+count);
}
}