malthe.w :
I've got an ArrayList of members, each with their own information including name, age, date of birth etc., which is called with a toString method when printed out to the terminal.
Here's the code:
@Override
public String toString() {
return "|ID: " + id + "| Name: " + name + "| Age: " +
calculateAge(age, LocalDate.now()) + "| Tlf.: " + tlfNo + "| Active: " +
activeMember + "| Next payment: " + nextPayment + "|";
}
And here's the output:
|ID: 12| Name: Casper| Age: 49| Tlf.: 12345678| Active: true| Next payment: 2018-02-12|
|ID: 13| Name: Allan| Age: 69| Tlf.: 12345678| Active: true| Next payment: 2018-01-12|
|ID: 16| Name: Christina| Age: 100| Tlf.: 12345678| Active: false| Next payment: 2018-02-04|
|ID: 19| Name: RICK| Age: 49| Tlf.: 12345678| Active: false| Next payment: 2018-04-14|
How do I get the different pieces of information to align on top of each other?
Veselin Davidov :
You can do something like:
public String toString() {
return String.format("|id: %10d |Name: %30s| Age: %02d | Tlf.: %d| Active: %s| Next Payment: %s |", id, getNameTrimmed() , age , tlfNo , activeMember, nextPayment );
}
private String getNameTrimmed(){
if(name.length()>30) {
return name.substring(0,27)+"...";
}
return name;
}
This way the id will have 10 characters (it will still break the format if you have longer IDs) The name will have 30 so you need to add a method to give you 30 chars name