#帮助。 Java 代码,获取5个学生的分数,用Arrays方法显示得A的学生

#Help. Java code, getting the marks of 5 students and displaying the students who got A using Arrays method

我有问题。我的任务是编写一个 Java 程序,使用数组方法接收 5 名学生的分数,然后查找并显示获得 A 级的学生人数。标记是 (60,56,78,99,92.5)。获得A级所需的标准是80分及以上。

我的代码中的一切都很顺利,除了最后一条语句: System.out.println("The number of students "+计数);

这是我的代码:

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("The number of students "+计数);

我收到一个错误:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type:

有没有人可以解释和纠正我的错误? :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); 
public class Q2 {

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);

    if(marks[i] >= 80.0) {
        count++;
    }
}
System.out.println("The number of students "+count); 
}

}

您的错误是您在循环内初始化了计数,并且在每次迭代中,编译器将值 0 分配给您的计数。把它放在循环上面。

您已在 loop.As 中声明并初始化了 count 变量,因此您将无法访问 count 变量之外的 loop.And 每次循环继续计数变量将分配给 0.Those 是你已经完成的两个错误。

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 变量。