更改数组的值

时间:2015-03-08 10:03:29

标签: java

每个学生都会有不同的考试成绩。每次创建新对象时,我如何能够更改该参数?是否有可能像双倍一样改变它的价值?我试过但它没用。感谢。

StudentData

 public class StudentData
{
  private NumberFormat fmt = NumberFormat.getCurrencyInstance();

  private String firstName;
  private String lastName;
  private double[] testScores;
  private char grades;
  public double average;
  public double total;

  public StudentData (String firstName, String lastName, double[] scores)
  {
   this.firstName = firstName;
   this.lastName = lastName;

   grades = courseGrade( scores);

   if (scores.length == 0)
    throw new IllegalArgumentException("There are no grades for this student");
   else
    testScores = scores;
 }

  public char courseGrade(double[] list)
 {

   for ( int x = 0; x < list.length; x++)
    total += list[x];
   average = total/list.length;
   if (average >= 90)
     return 'A';
   if (average < 90 && average >= 80)
     return 'B';
   if (average < 80 && average >= 70)
     return 'C';
   if (average < 70 && average >= 60)
     return 'D';
   else
     return 'F';

 }

 public String toString()
 {
  return firstName + "    " + lastName + "   " + fmt.format(testScores);
 }

}

TestProgStudentData

public class TestProgStudentData
{
  public static void main(String[] args)
  {
    double[] scores;
    List<StudentData> students = new ArrayList<StudentData>();
    scores = {79.00, 94.00, 86.00, 72.00, 90.00};
    students.add(new StudentData("Gaby", "Gomez", scores));
    scores = {85.00, 67.00, 86.00, 100.00, 93.00};
    students.add(new StudentData("David", "Gomez", scores));

   for(StudentData f : students)
     System.out.println(f);

   }
}

4 个答案:

答案 0 :(得分:0)

如果您想在不创建新对象的情况下更改分数的值,那么您应该添加一个新功能来执行此操作:

public void changeScore(int index, double newScore)
{
    this.testScores[index] = newScore;
}

答案 1 :(得分:0)

数组常量只能用于初始值设定项。编译器无法识别数组的类型。

例如:

“a = {...}”编译器不清楚

的类型
Object[] a;
a = {"Hello", "World"}; // use String[] or Object[] ?

它可以查看声明的类型(所以Object []),但因为它仍然不明确,编译器不允许它。

这是您搜索Why can array constants only be used in initializers?

的内容

答案 2 :(得分:0)

我会将arrayList完全更改为更好的选择。你必须稍微调整你的程序,但它可能会更好:

StudentData student1 = new StudentData("Gaby", "Gomez", 79.00, 94.00, 86.00, 72.00, 90.00);

System.out.println(student1);

答案 3 :(得分:0)

更改您的StudentData以接受新的varargs ...参数列表

public StudentData (String firstName, String lastName, double... scores)
  {
   this.firstName = firstName;
   this.lastName = lastName;

   grades = courseGrade( scores);

   if (scores.length == 0)
    throw new IllegalArgumentException("There are no grades for this student");
   else
    testScores = scores;
 }

然后将测试更改为

students.add(new StudentData("Gaby", "Gomez", 79.00, 94.00, 86.00, 72.00, 90.00));