0

我试图弄清楚为什么我的测试程序在主方法中的实例化对象中被调用时似乎完全跳过了公共类方法。请参阅下面的“Test”类和“Main”类,其中 main 方法创建对象并尝试调用所有三个类方法。

主类:

class Main {
  public static void main(String[] args) {
    Test test = new Test();
    test.getNumOfStudents();
    test.getGrades();
    System.out.println("The average grade is " + test.calcAvgGrade() + ".");
  }
}

测试类:

import java.util.*;

public class Test {
  
  public int numOfStudents;
  public double averageGrade;
  public double totalGrade;
  public Scanner input = new Scanner(System.in);

  public void getNumOfStudents() {
    System.out.println("How many students are enrolled?");
    this.numOfStudents = input.nextInt();
    return;
  }

  public void getGrades() {
    for(int i = 1; i == this.numOfStudents; i++) {
      System.out.print("Enter the grade of student # " + i + ":");
      this.totalGrade = input.nextDouble() + this.totalGrade;
      System.out.println("");
    }
    return;
  }

  public double calcAvgGrade() {
    this.averageGrade = this.totalGrade / this.numOfStudents;
    return this.averageGrade;
  }

}
4

2 回答 2

2

当你运行你的 for 循环时,你有条件 be i==this.numOfStudents。我认为你正在努力弥补this.numOfStudents

所以要解决这个问题,你将有一个小于或等于。所以你会有i<=this.numOfStudents,因为现在你的 for 循环是说只运行 if i==this.numOfStudents

于 2020-08-21T03:16:29.343 回答
0

在 methodgetGrades中,for 循环应该是:


   for(int i = 1; i <= this.numOfStudents; i++) {
         System.out.print("Enter the grade of student # " + i + ":");
         this.totalGrade = input.nextDouble() + this.totalGrade;
         System.out.println("");
       }

因为i == this.numOfStudents,你有问题。

于 2020-08-21T03:18:13.380 回答