user3006216
user3006216

Reputation: 43

I need to format a string from an array so it is appropiate

I need to print from an array so that it has columns but even after looking around online I cannot figure this out. I have the following code:

public void printDirectory() {
        System.out.println("Surname " + "Initial    " + "Extension");
        for (int i = 0; i < directory.length; i++) {
            System.out.println(directory[i]);

        }
    }

    public static void main(String[] args) {
        ArrayDirectory r = new ArrayDirectory();
        r.inputEntries();
        r.printDirectory();

    }

The program inputs data from a text file where there are Surnames, initials and a telephone extension. For example, I have "Smith J 0583" (There will be a number of these in the array all of different lengths) when I print them out I get very badly formatted output. I am aware that it is possible to format in Java but i am not sure how to use it since the string is all in one place.

Thank you for your help.

Upvotes: 0

Views: 75

Answers (1)

kabb
kabb

Reputation: 2502

You can use System.out.format to do this.

Using Java formatting, you can specify the lengths of Strings. So, you can make each column a set length in characters to make it format well. The only caveat is that you need to know the maximum length surname can be. In this example, i'll just guess 12.

String formatString = "%12s %7s %9s\n";
System.out.format(formatString, "Surname", "Initial", "Extension");
System.out.format(formatString, (Object[]) directory[i].split(" "));

What the formatString does is it specifies 3 strings, one that is 12 characters in length, then 7 characters in length, then 9 characters in length, all separated by spaces. Then, it ends with a new line. When you input three strings using this, they'll always be the same lengths, as long as none go over the length, which makes for nice formatting.

Upvotes: 1

Related Questions