Reputation: 177
I have tried the String formatter in my toString to make my output look fine, Anyone knows how I can fix this, I'm a new user of formatter in Java.
I'm using this code to read data from a file in ".ser" format The code looks like this,
public void printList(List<Person> list, File filepath) throws IOException, ClassNotFoundException {
Person person = new Person();
if (filepath.isFile()) {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(filepath));
list = (List<Person>) inputStream.readObject();
inputStream.close();
ListIterator iterator = list.listIterator();
int count = 0;
while (iterator.hasNext()) {
System.out.println((count +1)+ ". " +iterator.next());
count++;
}
if(count > 0){
System.out.println("\nThere are : " + count +" persons.\n");
}else {
System.out.println("The list is empty....!\nTo add to list enter 1:");
}
}
}
I'm using ObjectInputStream and OutPutstream for reading these data. My code works fine however the output I like to fix is in better shape.
public class Person extends Addresses implements Serializable {
private String firstName = "";
private String lastName = "";
private String age= "";
private double length;
private String postAddress = "";
private String postNumber = "";
private String postArea = "";
public Person() {
this("", "", "", 0.0, "", "", "");
}
public Person(String firstName, String lastName, string age, double length, String postAddress, String postNumber, String postArea) {
super(postAddress, postNumber, postArea);
this.firstName = firstName;
this.lastName = lastName;
this.signature = age;
this.length = length;
}
@Override
public String toString() {
String header = String.format(java.util.Locale.US, "\t%5s \t%1s %1s \t%10.2f",
this.age, this.firstName, this.lastName, this.length);
return header;
}
No Age Name Length[M]
1. 12 John Doe 1.80
2. 32 Mona lisa 1.69
3. 50 Benjamin Franklin 1.75
4. 45 Robert Oppenheimer 1.82
The output I want is
No Age Name Length[M]
1. 12 John Doe 1.80
2. 32 Mona lisa 1.69
3. 50 Benjamin Franklin 1.75
4. 45 Robert Oppenheimer 1.82
Upvotes: 3
Views: 245
Reputation: 101
solution 1: You can increase the string limit in such a way that all the resultant strings fits in the given limit so that uniform tab indentation will be there.
solution 2: you can limit the char limits like below so that always the string will be in given limit so proper indentation will be ther
String result = String.format("|%.5s|", "Hello World");// output -> |Hello|
Upvotes: 1