I need to design a class named Time. The class needs to contain:
■ Data fields hour, minute, and second that represent a time.
■ A no-arg constructor that creates a Time object for the current time. (The values of the data fields will represent the current time.)
■ A constructor that constructs a Time object with a specified elapsed time since midnight, Jan 1, 1970, in milliseconds. (The values of the data fields will represent this time.)
■ A constructor that constructs a Time object with the specified hour, minute, and second.
■ Three get methods for the data fields hour, minute, and second, respectively.
■ A method named setTime(long elapseTime) that sets a new time for the object using the elapsed time.
For this task, I have created the following code:
public class Time{
private int hour;
private int minute;
private int second;
public Time(){
this(System.currentTimeMillis());
}
public Time(long elapseTime){
long totalSeconds = elapseTime / 1000L;
this.second = (int)(totalSeconds % 60L);
long totalMinutes = totalSeconds / 60L;
this.minute = (int)(totalMinutes % 60L);
int totalHours = (int)(totalMinutes / 60L);
this.hour = (totalHours % 24);
}
public String toString() {
return this.hour + ":" + this.minute + ":" + this.second + " GMT";
}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public int getSecond() {
return this.second;
}
}
It compiles fine, but when I go to run it a dialog box pops up that says "No main methods, applets, or MIDlets found in file". Obviously my main method isn't right, but I can't seem to fix it, cause everything I've tried just creates more errors. If anyone could suggest a change to make my code work, I'd greatly appreciate it.
Edit: Yes, I orginally had it thusly:
public class Time{
public static void main(String args[]){...
but that had about a million errors. It seems I have the meat of it, but not the basic beginnings right.
You either need a main method in the Time class, or a separate class (ie "TimeTester") like this:
public class TimeTester {
public static void main(String[] args) {
// Test the default constructor
Time time = new Time();
System.out.println("time = " + time);
System.out.println("time.toHour() " + time.toHour());
// etc..
// Test with a supplied value
Time time2 = new Time(12033312L);
System.out.println("time2 = " + time2);
// etc..
}
}