Bill Bumbleton
Bill Bumbleton

Reputation: 25

Putting a variable in a printf Statement

I'm trying to make a method that will print a multi-dimensional array of strings into a table, with the amount of minimum spaces in each box of the table decided by a integer parameter. My thought was to simply put the variable name into where the number value would go in the printf statement, but this didn't work. Is there a way to put a variable into a printf statement like this?

Here is the example multidimensional array I used:

Static String[][] multi =  { {"cow", "horseshoe", "goat"}, 
{"billybob", "frededmenton", "al"},
{"apple"}, };

Here is the method call:

printMultiStringTable(multi, "Example Header", 5);

Here is the method I currently have:

public static void PrintMultiStringTable(String[][] table, String header, int boxSize) {
    System.out.printf("%s\n", header); //Prints a header at the top
    for (int i = 0; i < table.length; i++) {
        System.out.printf("%s", "|"); // Prints a vertical line at the start of each line
        for(int j = 0; j < table[i].length; j++) { 
            System.out.printf("%boxSizes", table[i][j]); // shoehorned in boxSize variable
            System.out.print("|");
        }
        System.out.println();
    }

}

The compiler can't read the variable when it is in the printf statement. Is there a way to put a variable in a printf statement like I tried to do here? If not, is there another way to change printf statements with parameters?

Errors: With boxSize as a variable it interprets the b as a boolean and returns:

 |trueoxSize|trueoxSize|trueoxSize|
 |trueoxSize|trueoxSize|trueoxSize|  
 |trueoxSize|

With a different variable minSize, it gives this error

Exception in thread "main" java.util.UnknownFormatConversionException: 
Conversion = 'm'
    at java.util.Formatter$FormatSpecifier.conversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
    at java.util.Formatter.parse(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.io.PrintStream.format(Unknown Source)
    at java.io.PrintStream.printf(Unknown Source)
    at test.printMultiStringTable(test.java:26)
    at test.main(test.java:15)

Upvotes: 0

Views: 2461

Answers (1)

Erk
Erk

Reputation: 1209

You must build the string like this:

System.out.printf("%" + boxSize + "s", table[i][j]);

Think of it as first creating a formatting string, and then using that string in the printf.

Upvotes: 4

Related Questions