To center a print statement text in Java, you can use a combination of spaces and the printf
method. The printf
method allows you to specify a format for the output, including the width of the output and the alignment of the text.
Here's an example of how you might use the printf
method to center a print statement text in Java:
String text = "Hello, World!"; int width = 20; System.out.printf("%-" + width + "s%n", text);
This code will print the text "Hello, World!" centered within a field of width 20. The output will look like this:
Hello, World!
You can adjust the width of the field and the text as needed. For example, to center a longer piece of text within a wider field, you can increase the width of the field and the length of the text.