-1

I have created a a basic table and am trying to format the tokens in the table to be under the Heading. Here is what I have:

NAME TYPE LINE#
a prod 1

This is what I would like:

NAME TYPE LINE#
a    prod 1

I know System.out.printf() would be the ideal way to format my string, but that does not work with my code which is in the main class. I have created an array of Strings and I use the .toString method I have created to print out (a prod 1). Here is my code:

for (int j = 0; j < numOfSym; j++) {
    System.out.println(symbols[j].toString());
}

Here is my symbol class:

public class Symbol {

    String type;
    String name;
    int lineNum;

    // toString method
    public String toString() {
        return name + " " + type + " " + Integer.toString(lineNum);
    }
}

The String.format does not work either. Would printf() be the best option? Any help or link would be helpful.

legoniko
  • 95
  • 1
  • 9
  • It's all in the Javadoc, but it will require some study. Please visit the [help] and read [ask] to learn the guidelines for posting here. Questions that can be answered by reading the (excellent) documentation are considered off-topic. – Jim Garrison Nov 08 '17 at 02:27

1 Answers1

1

Like?

System.out.println("NAME  TYPE  LINE# ");
String[][] data = {{"a", "prod", "1"}, {"b", "prod", "2"}};        

for (int i = 0; i < data.length; i++) {
    System.out.println(String.format("%-5s %-5s %-5s", data[i][0], data[i][1], data[i][2]));
}

or if you prefer (within your Symbol class):

@Override
public String toString() {
    return String.format("%-5s %-5s %-5s", type, name, lineNum);
}
bsaverino
  • 1,221
  • 9
  • 14