In: Computer Science
In JAVA please!
The log class will allow to store multiple string messages but one at a time (via record(..)), and also get back the whole sequence of messages (via read()).
assume and gurantee that each message is a single line of text.
the fields can be of my/your choice
four different methods in this class include;
public Logger() . establishes a new and empty log.
public Log duplicate() . this is not a constructor, but creates a no-aliases copy of this log and returns it. This becomes useful for when sharing the information without allowing modification.
public String[] read() . this will return an array of strings where each item in the array is the next line of the recorded content.
public void record(String msg) . this will record the given message as the next line in the log file.
here you will assume there are no newline characters in the message (the behavior is not defined if they are present; this means they must not be accounted for but if you want you can)
// Online URL for testing: http://ideone.com/BikSrN
import java.util.*;
class Log{
private ArrayList<String> msgs;
public Log(){
msgs=new
ArrayList<String>();
}
public Log duplicate(){
Log dup=new Log();
dup.msgs.addAll(this.msgs);
return dup;
}
public String[] read() {
return msgs.toArray(new
String[msgs.size()]);
}
public void record(String msg) {
msgs.add(msg);
}
}
class TestMain{
public static void main(String args[]){
Log t=new Log();
t.record("Log1 : Message Record
1");
t.record("Log1 : Message Record
2");
t.record("Log1 : Message Record
3");
for(String s:t.read()){
System.out.println(s);
}
System.out.println("Duplicating Log");
Log d=t.duplicate();
d.record("Log2 : Message Record
4");
d.record("Log2 : Message Record
5");
for(String s:d.read()){
System.out.println(s);
}
}
}