- It is better to represent the data as an object(of a class).
- The object can be printed as per the need
The following code will
- Define a new class
Schedule
to represent the record
- Schedule can override
toString
method to print its internal state
- The
toString
can use a Formatter
if needed
- Create multiple
Schedule
objects and print them using the toString
- Print the column before printing the actual objects (this is where my implementation is slightly offtrack)
import java.util.ArrayList;
import java.util.List;
public class ScheduleFormatter {
static class Schedule {
public static final String FORMAT = "%-15s %-20s %s";
private final int period;
private final String className;
private final String comment;
public Schedule(int period, String className, String comment) {
this.period = period;
this.className = className;
this.comment = comment;
}
@Override
public String toString() {
return String.format(FORMAT, this.period, this.className, this.comment);
}
}
public static void main(String[] args) {
List<Schedule> schedules = new ArrayList<>();
schedules.add(new Schedule(1, "Precalculus", "Boring"));
schedules.add(new Schedule(2, "Java", "Cool"));
System.out.println(String.format(Schedule.FORMAT, "Period", "Class", "Comment"));
schedules.forEach(System.out::println);
}
}
Even the List can be contained in another object and that container object can override the toString
.
import java.util.ArrayList;
import java.util.List;
public class ScheduleFormatter {
static class Schedule {
public static final String FORMAT = "%-15s %-20s %s\n";
private final int period;
private final String className;
private final String comment;
public Schedule(int period, String className, String comment) {
this.period = period;
this.className = className;
this.comment = comment;
}
@Override
public String toString() {
return String.format(FORMAT, this.period, this.className, this.comment);
}
}
static class Schedules {
private String[] headers;
private List<Schedule> schedules;
Schedules(String[] headers) {
this.headers = headers;
this.schedules = new ArrayList<>();
}
public void add(Schedule schedule) {
this.schedules.add(schedule);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(String.format(Schedule.FORMAT, headers));
schedules.forEach(builder::append);
return builder.toString();
}
}
public static void main(String[] args) {
Schedules schedules = new Schedules(new String[] {"Period", "Class", "Comment"});
schedules.add(new Schedule(1, "Precalculus", "Boring"));
schedules.add(new Schedule(2, "Java", "Cool"));
System.out.println(schedules);
}
}