Java Output Formatting for Strings

Java output formatting for Strings

EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though

Why not just generate a whitespace string dynamically to insert into the statement.

So if you want them all to start on the 50th character...

String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);

Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.

How can i use printf in java to to print formatted output

Use String's format to format strings the way "sprintf" does in C.

From that reference, adapting to your need:

  • Padding left with zeros:

    String.format("|%03d|", 93); // prints: |093|
  • String of spefiied length (involves max and min)

    String.format("|%-15.15s|", "Hello World"); |Hello World   |

    You want left justified so "-N" instead of N for first value

Java 8's official format reference: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-

And format string documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

How to format string output java

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);
}

How to format string output, so that columns are evenly centered?

I'm also going with the "format" suggestion, but mine is a little different.

In your program, you're relying on your card's toString. So make that formatted in a fixed length, and then you can use them anywhere and they will take up the same space.

public String toString() {
return String.format( "%5s of %-8s", rank, suit );
}

When you print this out, you'll have all your cards aligned on the "of" part, which I think is what you were going for in your first output column.

The "%5s" part right-aligns the rank in a field 5 characters wide, and the "%-8s" part left-aligns the suit in a field 8 characters wide (which means there are additional spaces to the right if the suit is shorter than 8 characters).

Formatting String Output in Java

String i1 = "Pepperoni", i2 = "Sausage", i3 = "Canadian Bacon";
String ingredients = i1 + "\n" + i2 + "\n" + i3;
System.out.println(ingredients);
System.out.println("Your pizza includes only these ingredients: " + ingredients.replace("\n", ", ")

Output in a table format in Java's System.out

Use System.out.format . You can set lengths of fields like this:

System.out.format("%32s%10d%16s", string1, int1, string2);

This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively.

See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).

How to format strings in Java

In addition to String.format, also take a look java.text.MessageFormat. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.

For example:

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });

Using Java string.format() for printing

String.format() roughly takes a first string argument that is the "layout" you desire, with specifiers that start with % representing the variable types (%s for string, %d for digit etc.) and the next series of arguments being the actual data - that should match the number of specifiers in the format layout in number and order:

    int[] years = new int[3];
int i = 0;
for (int year = 1999; year < 2045; year++) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
years[i++] = year;
if (i > 2) {
System.out.println(String.format("%d,%d,%d", years[0], years[1], years[2]));
i = 0;
}
}
}

2000,2004,2008
2012,2016,2020
2024,2028,2032
2036,2040,2044

String.format() feels like overkill for this situation though. You could (approximately) accomplish the same task in my particular solution without the need for format by just using:

 System.out.println(Arrays.toString(years));

except that there would also be square brackets around the int array used in this example.

[2000, 2004, 2008]
[2012, 2016, 2020]
[2024, 2028, 2032]
[2036, 2040, 2044]


Related Topics



Leave a reply



Submit