Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Solutions to Java Lab 6 
 
1. Add appropriate access modifiers to all your fields and methods in GradebookOO 
and GBProgram. Compile. 
 
2. Add a method to GradebookOO called addGrade which accepts a double 
argument and adds it to the array of grades. This is difficult.  Two things you should note: 
• arrays always have the same length, so you can't increase it the size of it 
• arrays are objects not primitives, so variables of type array hold references to arrays 
 
3. Delete the GradebookOO constructor that takes an array of doubles as an argument. 
And change the main method of GBProgram so that it instantiates an empty 
GradebookOO and adds the grades one-by-one to it with the addGrade method. 
Compile and run. 
 
class GradebookOO { 
 
   private double grades[]; 
 
   public GradebookOO() { 
      grades = new double[0]; 
   } 
 
   public void printGrades() { 
      for(int i = 0; i < grades.length; i++) { 
         System.out.println(grades[i]); 
      } 
   } 
 
   public double averageGrade() { 
      double total = 0; 
      for(int i = 0; i < grades.length; i++) { 
         total += grades[i]; 
      } 
      return total / grades.length; 
   } 
 
   public void addGrade(double g) { 
       double[] temp = new double[grades.length + 1]; 
       for(int i = 0; i < grades.length; i++) { 
           temp[i] = grades[i]; 
       } 
       temp[grades.length] = g; 
       grades = temp; 
   } 
} 
 
class GBProgram { 
 
    public static void main(String args[]) { 
 
        GradebookOO gbook = new GradebookOO(); 
        for (int i = 0; i < args.length; i++) { 
            double g = Double.parseDouble(args[i]); 
            gbook.addGrade(g); 
        } 
 
        gbook.printGrades(); 
        double average = gbook.averageGrade(); 
        System.out.println("Your average grade is " + 
                           average); 
    } 
} 
 
5. (Optional) Add a method deleteGrade to GradebookOO which accepts a grade as 
an argument and removes it from the array if it's there. This is tricky. Compile and run. 
 
    public void deleteGrade(double g) { 
        int gIndex = 0; 
        for(; gIndex < grades.length; gIndex++) { 
            if (grades[gIndex] == g) break; 
        } 
 
        if (gIndex == grades.length) return; 
 
        double[] temp = new double[grades.length - 1]; 
        for(int i = 0; i < gIndex; i++) { 
            temp[i] = grades[i]; 
        } 
        for(int i = gIndex + 1; i < grades.length; i++) { 
            temp[i - 1] = grades[i]; 
        } 
 
        grades = temp; 
    }