简体   繁体   English

用Java创建类时遇到麻烦。 不确定某些方法

[英]Having trouble creating a class in Java. Not sure on some of the methods

ok so this is the assignment that I'm working on: 好的,这是我正在处理的作业:

"Implement a class Student (you may use the one you created for lab and add on to it). In addition to any other attributes that the class already has, the student object will have a total quiz score. Be sure to write a complete class (ie proper attributes, constructor, accessors and mutators). “实施一班学生(您可以使用您为实验室创建的班级并添加到该班级上。)除了该班级已有的其他属性外,该学生对象还将获得总测验成绩。请务必写完整的测验分数。类(即适当的属性,构造函数,访问器和变异器)。

Other methods needed are: addQuiz(int score), showStudentInfo(), and getAverageScore(). 其他需要的方法是:addQuiz(int score),showStudentInfo()和getAverageScore()。 Note that in order to calculate average, the class needs to know the number of quizzes. 注意,为了计算平均值,班级需要知道测验的数量。 The driver/tester class will create three (3) student objects. 驾驶员/测试员课程将创建三(3)个学生对象。 Each student object's method will be called five times to add five (5) quiz grades. 每个学生对象的方法将被调用五次,以增加五(5)个测验成绩。

I recommend that you use Random class to generate the quiz values, instead of hard-coding them.Then the driver calls Student's method to display the students' name, all five quiz grades, and the average score of the quizzes." 我建议您使用Random类来生成测验值,而不是对其进行硬编码。然后,驱动程序调用Student的方法来显示学生的姓名,所有五个测验成绩以及测验的平均分数。”

I have a basic idea of what needs to be done but I'm just unsure on some of the methods. 我对需要做什么有一个基本的想法,但是我不确定其中的一些方法。 For example the "getAverageScore" method is the one that I'm having trouble with. 例如,“ getAverageScore”方法是我遇到麻烦的方法。 Also do I even need the get and set methods for age name and major if I'm am just initializing them at the beginning of the tester program? 如果我只是在测试程序开始时初始化年龄和专业的年龄,我是否还需要get和set方法? Any help on what needs to be added or fixed with my class is greatly appreciated. 非常感谢对我班上需要添加或修复的内容的任何帮助。 Here is the code that I have so far: 这是我到目前为止的代码:

import java.util.Random;

public class Student
{
  private int Age;
  private String Name;
  private String Major;
  private int Score;

  public Student(String n, int a, String m)
  {
    Name = n;
    Age = a;
    Major = m;
  }

  public String showStudentinfo()
  { return (Name + " " + Age + " " + Major + "\n");
  }

  public int addQuiz()
  { Score = randomNumbers.nextInt(101);
    return Score;
  }

  public int getAverageScore()
  { 
  }

  //setter methods
  public void setAge(int a)
  { Age = a;
  }
  public void setName(String n)
  { Name = n;
  }
  public void setMajor(String m)
  { Major = m;
  }

  //getter methods
  public int getAge()
  { return Age;
  }
  public String getName()
  { return Name;
  }
  public String getMajor()
  { return Major;
  }
}

Most of it looks fine, but there are a couple issues, mostly style-related (maybe a bit subjective). 大部分看起来不错,但是有几个问题,大部分与样式有关(可能有点主观)。

1) You don't initialize randomNumbers anywhere. 1)您不会在任何地方初始化randomNumbers。

2) Variable names should start with lower case letters. 2)变量名称应以小写字母开头。 Capitalized names are generally reserved for classes. 大写名称通常为类保留。

3) Don't use single letter variable names, even for arguments. 3)即使对于参数,也不要使用单字母变量名称。 They're annoying and obscure information. 它们令人讨厌且晦涩难懂。 Use something more informative like setAge(int newAge). 使用更有用的信息,例如setAge(int newAge)。

4) It sounds like they want you to store the sum of all test scores (which is weird, but hey) and then calculate the average. 4)听起来好像他们要您存储所有测试成绩的总和(这很奇怪,但是嘿),然后计算平均值。 To get the average from a sum you're going to need to know how many tests are included in the sum, so you'll have to keep track of that somewhere and increment it accordingly. 要从总和中获取平均值,您将需要知道总和中包含多少个测试,因此您必须跟踪某个位置并相应地对其进行递增。 In addQuiz right now you're just keeping track of the score of the most recent quiz. 现在在addQuiz中,您只是在跟踪最新测验的分数。

5) Don't start the body of a function on the same line as the {, it's ugly. 5)不要在与{相同的行上启动函数的主体,这很难看。

In order for getAverageScore() to work, you'll need to keep track of individual scores. 为了使getAverageScore()起作用,您需要跟踪各个分数。 You could do something like use an ArrayList<Integer> and add individual scores to them. 您可以执行类似的操作,例如使用ArrayList<Integer>并向其中添加单个乐谱。 (Alternatively, you could keep an avgScore attribute, along with a numOfTests attribute, and compute the new average from that---though if you want the average as an int this could become more inaccurate over time). (或者,你可以保持一个avgScore属性,具有沿numOfTests属性,并从计算的新的平均---但如果你想平均为int这可能会随着时间变得更为准确)。

Here is part of a solution that relies on ArrayList<Integer> . 这是依赖ArrayList<Integer>的解决方案的一部分 I assume here your method signature is correct, and you don't actually want to return a double or float (ie you're going to have to round up/down the score). 我在这里假设您的方法签名是正确的,并且您实际上并不想返回doublefloat (即,您将不得不舍入/降低分数)。

public int getAverageScore() {
    float sum = 0.0; // so rounding works, integer division truncates
    // in case you're not familiar with it,
    // read the following line as "for each score in scoreList"
    for (Integer score : scoreList) { // scoreList is of type ArrayList<Integer>
       sum = sum + score;
    }
    return Math.round(sum / scoreList.size());
}

Now, I don't show you how to properly implement scoreList , as this is homework and you should still do some of it yourself. 现在,我不向您展示如何正确实现scoreList ,因为这是家庭作业,您仍然应该自己做一些。 A hint: You can't use primitive types (like int ) in an ArrayList , you'll need to instead store Integer s. 提示:不能在ArrayList使用基本类型(如int ),而需要存储Integer You can create an integer of a particular value with new Integer(int value) . 您可以使用new Integer(int value)创建具有特定值的new Integer(int value) If, instead, you knew there were going to be a fixed number of scores, you could use an int array. 相反,如果您知道分数将是固定的,则可以使用int数组。

For this solution to work, you'll need to add the scoreList attribute, and you'll need to change how addQuiz() works. 为了使该解决方案有效,您需要添加scoreList属性,并且需要更改addQuiz()工作方式。

fields should start with a lower case. 字段应以小写开头。 Setters are not mandatory, it just depends if it makes sense or not. 设置程序不是强制性的,仅取决于是否有意义。 Methos addQuiz should take an int as an argument and you should have a field int numberOfQuizzes. 方法addQuiz应该将int作为参数,并且您应该将int numberOfQuizzes作为字段。 That field should be incremented everytime a quiz score is added. 每次添加测验分数时,都应增加该字段。 The average score is then just the total of the scores divided by the number of quizzes 然后,平均分数就是分数的总和除以测验的数量

You must keep sum of all scores and number of quizes taken, so add 2 fields, sumOfQuizGrades and countOfQuizGrades , and by method addQuiz add the grade to sum and increment the count. 您必须保留所有分数的总和和参加的测验的数量,因此添加2个字段sumOfQuizGradescountOfQuizGrades ,并通过方法addQuiz将分数相加以求和并递增计数。

By the way don't change the signature of the addQuiz it must not hold the random within it, the random shall be added in main method. 顺便说一下,不要更改addQuiz的签名,它不能在其中包含随机数,应在main方法中添加随机数。

You need to store the quiz grades somewhere. 您需要将测验成绩存储在某个地方。 Your professor said there would be more than one. 你的教授说会有不止一个。 Above the 'Student' constructor, add either an Array of size 5 or an ArrayList. 在“学生”构造函数上方,添加大小为5的数组或ArrayList。 I will use an Array for this, so: 我将为此使用数组,因此:

private int[] scores = new int[5];

Then in your method that gets the scores, add them to the Array with a Loop: 然后在获取分数的方法中,使用循环将其添加到数组中:

public void addQuiz() { 
    for(int i = 0; i < 5; i++){ //Loops through and adds 5 scores
    int score = randomNumbers.nextInt(101);
    scores[i] = score;
    }
}

Then you should be able to calculate the average of the scores by adding the grades together and dividing them by 5: 然后,您应该能够通过将成绩加在一起并除以5来计算分数的平均值:

public int getAverageScore() {
    int totalScore = scores[0] + scores[1] + scores[2] + scores[3] + scores[4];
    int avgScore = totalScore / 5;
    return avgScore;
}

I have not actually tested this code, and I am a beginner myself, but hopefully this puts you on the right track. 我实际上尚未测试过此代码,而我本人还是新手,但是希望这可以使您走上正确的道路。 :) :)

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

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