I\'m trying to format two arrays in Java to print something like this:
Inventory Number Books Prices
--------------------------
You should look at format:
System.out.format("%15.2f", booksPrices[i]);
which would give 15 slots, and pad it with spaces if needed.
However, I noticed that you're not right-justifying your numbers, in which case you want left justification on the books field:
System.out.printf("%-30s", books[i]);
Here's a working snippet example:
String books[] = {"This", "That", "The Other Longer One", "Fourth One"};
double booksPrices[] = {45.99, 89.34, 12.23, 1000.3};
System.out.printf("%-20s%-30s%s%n", "Inventory Number", "Books", "Prices");
for (int i=0;i<books.length;i++){
System.out.format("%-20d%-30s$%.2f%n", i, books[i], booksPrices[i]);
}
resulting in:
Inventory Number Books Prices
0 This $45.99
1 That $89.34
2 The Other Longer One $12.23
3 Fourth One $1000.30
You can use
System.out.printf(...)
for formatting the output. That uses
String.format(...)
which uses
java.util.Formatter
you can find the documentation here.
To align a simple String, you can use the following:
String formatted = String.format("%20s", str)
this will prepend
20 - str.length
blanks before the actual String and will return the padded String. For example, if your String is "Hello, World!" it will prepend 11 blanks:
" Hello, World!"
to align something to the right left, you have to prepend a "-" before the number that indicates the length of the result string.
To safely align everything, you first have to find out what is your longest string.
Without using any libraries, you need to determine the maximum length of each coloumn and append the needed space characters appropriately. For example like this:
/**
* Determines maximum length of all given strings.
*/
public static int maxLength(int padding, String... array) {
if (array == null) return padding;
int len = 0;
for (String s : array) {
if (s == null) {
continue;
}
len = Math.max(len, s.length());
}
return len + padding;
}
/**
* Unifies array element lengths and appends 3 whitespaces for padding.
*/
public static String[] format(String[] array) {
if (array == null || array.length == 0) return array;
int len = maxLength(3, array);
String[] newArray = new String[array.length];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
while (newArray[i].length() < len) {
newArray[i] += " ";
}
}
return newArray;
}