COMP 110 Spring 2011

In-class exercise: Methods

February 23, 2011

Description

The purpose of this exercise is to give you some practice in writing methods in classes. Given the code in StudentMain.java (see below), write a class Student that has the necessary instance variables and methods for the code in StudentMain to run. Start off by first writing the UML diagram for the Student class (should look similar to notes from Monday). Then translate the UML diagram into code.

  • Give each variable a name and a data type
  • Name each method as it is in StudentMain and give it the proper return type.
  • Write code for Student class - remember that this would go in a separate file called Student.java if you were writing it in Eclipse.
  • Assume that the method printData() uses System.out.println() statements to output the student's name, class year and major.
  • The increaseYear method should check for the following:
  • After writing the code for the Student class, write down what StudentMain.java will output.
  • This exercise will not be graded. We will discuss it later. You are welcome to work in groups, but make sure you understand the concepts. Ask questions if you are having trouble.






    import java.util.*;

    public class StudentMain
    {
        public static void main(String[] args)
        {
             Student s1 = new Student();
             Student s2 = new Student();
            
             s1.setName("John Doe");
             s1.setClassYear(1);
             s1.setMajor("Computer Science");
            
             s1.increaseYear();
            
             s2.setName("Jane Doe");
             s2.setClassYear(3);
             s2.setMajor("Physics");
            
            
             System.out.println("Student 1");
             s1.printData();
            
             System.out.println("Student 2");
             s2.printData();
         }
    }