Part A: A Timer Program
The following program:
package timer;
public class Timer
{
public void main(String[] args)
{
Timer m = new Timer();
}
public Timer()
{
m_start = new Time(0);
m_end = m_start;
m_end.addSeconds(45);
System.out.println("Started at " + m_start);
System.out.println("Ended at " + m_end);
System.out.println("Duration = "
+ m_end.secondsBetween(m_start)
+ " secs");
}
////////////// Data ///////////////
private Time m_start, m_end;
}
class Time
{
public Time(long sec)
{
m_sec = sec;
}
public void addSeconds(long sec)
{
m_sec += sec;
}
public long secondsBetween(Time t)
{
return m_sec - t.m_sec;
}
public String toString()
{
return "Time: " + m_sec + " secs";
}
/////////////// Data ///////////////
private long m_sec;
}
|
is intended to be a rudimentary application (not an
applet) which times the duration between two events.
It compiles, but unfortunately refuses to run.
Fix the program so that it will compile and run as an
application.
Hint:
There is a single problem only. It is a simple case of
omission -- one that is quite a common mistake!
When you finally get the program to run, you will find
that it produces the following output:
Started at Time: 45 secs
Ended at Time: 45 secs
Duration = 0 secs
|
Fix the program so that it prints out the
correct duration.
Now comment out the entire toString()
method in the Time
class, and recompile and run the program.
Hint 1:
Change the lines in the program that read:
System.out.println("Started at " + m_start);
System.out.println("Ended at " + m_end);
to read:
System.out.println("Started at " + m_start.toString());
System.out.println("Ended at " + m_end.toString());
What effect does this have? Why?
Hint 2:
Use the IDE help or JDK documentation to find the toString() method. You'll see that there are many
of them, in different classes. Take special note of the toString() method in the
java.lang.Object class.
|