CSC212 Examples for Lecture 3

From dftwiki3
Revision as of 10:18, 10 September 2014 by Thiebaut (talk | contribs) (Student Class)
Jump to: navigation, search

--D. Thiebaut (talk) 11:14, 10 September 2014 (EDT)


Student Class


/**
 * Student: A class implementing a student with a name and age.
 */
public class Student {
	String name = "";
	int age = 0;
	static int MAX = 5; // max number of students in array
	
	/**
	 * Constructor: initializes both the name and age
	 * @param n: the name
	 * @param a: the age
	 */
	Student( String n, int a ) {
		name = n;
		age  = a;
	}
	
	/**
	 * displays the name and age nicely formatted.
	 */
	public void display() {
		System.out.println( 
				String.format( "Student: %5s: %d years old", 
						name, age ) );
	}
	
	/**
	 * main entry point. 
	 * @param args
	 */
	public static void main(String[] args) {
		//--- array of students ---
		Student[] students = new Student[MAX];
		
		//--- Create MAX students and store in array students ---
		int i;
		char n;
		for ( i=0, n='a'; i<MAX; n++, i++ ) {
			students[i] = new Student( "" + n, i+20 ); // trick: string + char --> string
		}
		
		//--- display all students ---
		for ( i=0; i<MAX; i++ ) 
			students[i].display();
	}

}