【问题标题】:Calculating a minimum in object arrays and then using it in another calculation计算对象数组中的最小值,然后在另一个计算中使用它
【发布时间】:2020-04-04 00:17:32
【问题描述】:

我正在尝试了解如何获取包含具有名称和 4 个数字的对象的对象数组并找到最低的测试成绩。我有这个 Student 对象,它有一个名字、获得的奖励积分、测试 1 级、测试 2 级和测试 3 级。我需要确保所有 3 个考试成绩加在一起不超过 300 分。

然后我需要找到每个学生输入的 3 个成绩中最低的考试成绩,然后能够将加分添加到他们身上并打印出新成绩。

我打算创建一个方法来遍历 Student 对象数组并找到每个学生的最低成绩,让它创建一个只有最低成绩的新数组并将其添加到每个学生获得的奖励积分中,但我'我实际上不确定如何去做那部分。这是迄今为止我创建的 Student 对象的代码:

public class Student
{
   private String name;
   private int bonusPoints;
   private int test1;
   private int test2;
   private int test3;
   public static final int MAX_TOTAL = 300;

   public Student(String n, int bP, int g1, int g2, int g3)
   {
      setName(n);
      setBonus(bP);
      setTest1(g1);
      setTest2(g2);
      setTest3(g3);
   }

    //Setters & getters

   //Method to check total of all 3 test grades
   public boolean checkTotal(Student[] array)
   {
      int total = 0;
      for (int i = 0; i < array.length; i++)
      {
         total += //I'm not sure how to refer to test1 ,test2, and test3 here
      }
      if (total > MAX_TOTAL)
      {
         return false;
      }
      else
      {
         return true;
      }
   }

}

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    因此,为了将 3 个测试总数相加并检查它是否超过最大值。我会做这样的事情。

    public boolean checkTotal()
    {
     int total = this.test1 + this.test2 + this.test3;
     return total > MAX_TOTAL;
    }
    

    当引用该类中的类变量时,您可以使用“this”关键字来引用该类的当前实例。 所以该对象的方法调用看起来像这样:

    Student studentOne = new Student("Foo",90,80,70,10);
    if(!studentOne.checkTotal())
     //do something
    else
     //do something else
    

    此外,在返回布尔值时,大多数情况下您不需要 if/else。你可以简单地把

    return /*your boolean expression here*/;
    

    【讨论】:

    • 哦,我想我过于复杂了,因为我试图传入整个对象数组并用它进行计算,结果让自己感到困惑。非常感谢您的帮助!
    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2015-10-19
    • 2015-08-31
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    相关资源
    最近更新 更多