简体   繁体   English

为什么这个简单的 Java 不能循环工作?

[英]Why isn't this simple Java for loop working?

I'm trying to figure out why my test program seems to be completely skipping a public class method when being called in an instantiated object in the main method.我试图弄清楚为什么我的测试程序在主方法中的实例化 object 中被调用时似乎完全跳过了公共 class 方法。 Please see below for both the "Test" class and the "Main" class where the main method creates the object and attempts to call all three class methods.请参阅下面的“测试”class 和“主要”class,其中主要方法创建 object 并尝试调用所有三个 ZA2F22ED4F8EBC26BDZ 方法

Main class:主class:

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() + ".");
  }
}

Test Class:测试 Class:

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

}

When you run your for loop, you have the condition be i==this.numOfStudents .当您运行 for 循环时,您的条件是i==this.numOfStudents I think you are trying to make it up to this.numOfStudents .我认为您正在努力弥补this.numOfStudents

So to fix this you would have a less than or equal to.所以要解决这个问题,你将有一个小于或等于。 So you would have i<=this.numOfStudents , because right now your for loop is saying run ONLY if i==this.numOfStudents .所以你会有i<=this.numOfStudents ,因为现在你的 for 循环说只在i==this.numOfStudents时运行。

In method getGrades , the for loop should be:在方法getGrades中,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("");
       }

Because of i == this.numOfStudents , you're having issues.由于i == this.numOfStudents ,您遇到了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM