Top
Previous Next
The Java Language CS 161 - Java

Last Week's Homework

Write the class Hello so that it prints on four lines just:

Source: examples/Hello.java



/** Hello.java
** Jonathan Doughty - assignment 1
** A Java class to produce output that looks like:
** Your name
** Your GMU ID
** Your email address
** The date and time
**/
 
// Will use a Date object from the java.util package.
import java.util.Date;
 
public class Hello {
 
public static void main(String[] args) {
 
// Make a Hello object ...
 
Hello anObject = new Hello();
 
// Initialize it
 
anObject.initialize();
 
// ... and ask it to to identify itself
 
System.out.println( anObject.toString() );
 
Hello.waitForUser();
}
 
// The rest of this relates to Hello "objects"
 
// each Hello object will remember who you tell it is using
// these "instance variables" named "name", "GMUid", "email"
 
String name;
String GMUid;
String email;
Date now;
 
public void initialize() {
 
// Assign its name from the command line argument
 
name = "Jonathan Doughty";
GMUid = "123-45-6789";
email = "jdoughty@cs.gmu.edu";
now = new Date();
}
 
// This will allow Hello objects to identify themselves asked.
 
public String toString() {
String result;
result = "Name:" + name +
"\nGMU Id:" + GMUid +
"\nEmail:" + email +
"\nDate:" + now;
return result;
}
 
// The following is only needed for running the program from
// within the Javaedit application on Windows
public static void waitForUser() {
try {
byte[] line = new byte[80];
System.out.println("press enter key to end");
System.in.read(line);
}
catch (java.io.IOException e) {
// ignored
}
 
}
}

Produces:

Name:Jonathan Doughty GMU Id:123-45-6789 Email:jdoughty@cs.gmu.edu Date:Sat Oct 30 21:31:57 EDT 1999 press enter key to end
Top
Previous Next
jwd