LAB 32 – Creating Classes (part 1)

Lab Exercises

Topics

n      To create a main method.

n      To define a class including the fields, constructors, and methods.

n      To overload constructors

n      To create and initialize an array

 

Exercises

11.6 Creating a MAIN Method

 

i) Type in the code for a main method that declares two student objects, asks the user for the student name and array of grades and then creates the two student objects.

 

Type in the following code in the Program window (changing the comments):

 

import java.util.Scanner;

/*  Program that manipulates student records (objects)

  *

  * @author Wayne Summers

  * @date   Nov. 5, 2007

  */

public class ProcessStudents

{

     public static void main (String[] args)

    {

       final int numberOfGrades = 3;

       Scanner scan = new Scanner(System.in);

       String name;

       double[]  grades = new double[numberOfGrades];

 

       System.out.println("Enter the first student name ");

       name = scan.nextLine();

       //Student student1 = new Student(name);   //creates student1

      

       System.out.println("Enter the second student name ");

       name = scan.nextLine();

       System.out.println("Enter the second student\'s " + numberOfGrades + " grades ");

       for (int index = 0; index < numberOfGrades; index++)

         grades[index] = scan.nextDouble();

       //Student student2 = new Student(name, grades);   //creates student2

     } 

 }

ii) Open a new file in Dr. Java and type in the following class:

 

/*  Student class

  *

  * @author Wayne Summers

  * @date   Nov. 5, 2007

  */

public class Student

{

  //////////////fields /////////////////

  private String name;

  private double[] gradeArray;

 

  //////////////constructors //////////

  public Student (String theName)

  {

    this.name = theName;

  }

 

  //////////////methods ///////////////

  public String toString()

  {

    String result = "Student\'s name is " + this.name;

    return result;

  }

}

 

iv) Modify your Student class by

a)                          adding another constructor that receives both theName and theGradeArray and assigns both to the fields of Student.

b)                          Modify the toString by adding a loop to append the grades to the name. Make sure to test if the array is NOT null

 

v)      Modify the main method by

a.       Removing the comments to instantiate the two students

b.      Add print statements to print the two students information [Note that this will call the toString in the Student class

 

QUESTIONS:

 

Submit the ProcessStudents.java and Student.java files through the DropBox in WebCT.