user2070292
user2070292

Reputation: 147

How to center a print statement text?

So I was working on my java project and in one part of the program I'm printing out text The text is displayed on the left side However I wanted it be displayed in the middle How many I accomplish this? Is this a newbie question?

Example:

public static void main(String[] args)
{
System.out.println("Hello");
}

Upvotes: 13

Views: 63219

Answers (7)

Laksitha Ranasingha
Laksitha Ranasingha

Reputation: 4517

If you have a definite line length, apache commons StringUtils.center will easily do the job. However, you have to add that library. javadoc

Upvotes: 2

Thomas Decaux
Thomas Decaux

Reputation: 22681

As lot of programming questions, dont reinvent the wheel!

Apache have a nice library: "org.apache.commons" that come with a StringUtils class:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

The pad method is what you want:

int w = 20;

System.out.println(StringUtils.rightPad("+", w - 1, "-") + "+");
System.out.println(StringUtils.center(StringUtils.center("output", w - 2), w, "|"));
System.out.println(StringUtils.rightPad("+", w - 1, "-") + "+");

will give you:

+----------------------+
|        output        |
+----------------------+

Upvotes: 2

Jonny Henly
Jonny Henly

Reputation: 4233

You could do something like:

public static void main(String[] args) {
    String h = "Hello";

    System.out.println(String.format("%-20s", h));
}

This approach outputs a string offset by a given number of spaces. In this case Hello is preceded by 20 spaces. The spaces precede Hello because the integer between % and s is negative, otherwise the spaces would be trailing.

Just mess with the integer between % and s until you get the desired result.

Upvotes: 1

marcelocra
marcelocra

Reputation: 2503

If you know the size and don't want to use an external library you could do something like this:

static void printer(String str, int size) {
    int left = (size - str.length()) / 2;
    int right = size - left - str.length();
    String repeatedChar = "-";
    StringBuffer buff = new StringBuffer();
    for (int i = 0; i < left; i++) {
        buff.append(repeatedChar);
    }
    buff.append(str);
    for (int i = 0; i < right; i++) {
        buff.append(repeatedChar);
    }
    // to see the end (and debug) if using spaces as repeatedChar
    //buff.append("$");  
    System.out.println(buff.toString());
}

// testing:

printer("string", 30);

// output:
// ------------string------------

If you call it with an odd number for the size variable, then it would be with one - more to the right. And you can change the repeatedChar to be a space.

Edit

If you want to print just one char and you know the size, you could do it with the default System.out.printf like so:

int size = 10;
int left = size/2;
int right = size - left;
String format = "%" + left + "c%-" + right + "c";
// would produce: "%5c%-5c"
System.out.printf(format,' ', '#');
// output: "     #    " (without the quotes)

The %-5c align the # character to the left of the 5 spaces assigned to it

Upvotes: 0

Ahmed Masud
Ahmed Masud

Reputation: 22402

VERY QUICK answer

You can use the JavaCurses library to do fun things on the console. Read below it's in there.

Before you do though let's answer your entire question in some context

It is a newbie question :) but it's a valid question. So some hints for you:

First question is, how wide is the terminal? (it's counted in number of characters) old terminals had a fixed dimensions of 80 characters and 25 lines;

So as a first step start with the assumption that it's 80 characters wide.

How would you center a string on an 80 character wide terminal screen?

Do you need to worry about the length of the string? How do you position something horizontally? Do you add spaces? Is there a format string you can come up with?

Once you've written a program such that you can give it any string that will display properly on those assumptions (that terminal is 80 characters wide) you can now start worrying about what happens if you are connected to a terminal which is more or less than 80 characters? Or whether or not you are even connected to a terminal. For example if you are not does it make sense to "prettify" your code? probably not.

So question is how do you get all this information?

What you are asking for is the ability to treat the console as a smart teletype (tty) terminal with character-based control capabilities. Teletype terminals of the old can do a lot of fun things.

Some history

Teletype terminals were complicated things and come from the legacy that there were a lots of terminal manufacturers (IBM, DEC, etc.) ... These teletype terminals were developed to solve lots of problems like being able to display content remotely from mainframes and minicomputers.

There were a bunch of terminal standards vt100, vt200, vt220, ansi, that came about at various points in terminal development history and hundreds of proprietary ones along the way.

These terminals could do positioning of cursors and windowing and colors, highlight text, underline etc. but not everyone could do everything. However this was done using "control" characters. ctrl-l is clear screen on ansi and vt terminals, but it may be page feed on something else.

If you wrote a program specific to one it would make no sense elsewhere. So the necessity to make that simple caused a couple of abstraction libraries to developed that would hide away the hideousness.

The first one is called termcap (terminal-capabilities) library, circa 1978, which provided a generic way to deal with terminals on UNIX systems. It could tell a running program of the available capabilities of the terminal (for example the ability to change text color) or to position cursor at a location, or to clear itself etc, and the program would then modify its behavior accordingly.

The second library is called curses, circa 1985 (??) it was developed as part of the BSD system and was used to write games ... One of the most popular versions of this library is the GNU curses library (previously known as ncurses).

On VMS I believe the library is called SMG$ (screen management library).

On with the answer

Any how, so you can use one of these libraries in java to determine whether or not you are working on a proper terminal. There is a library called JavaCurses on source forge that provides this capability to java programs. This will be an exercise in learning how to utilize a new library into your programs and should be exciting.

JavaCurses provides terminal programming capability on both Unix and Windows environments. It will be a fun exercise for you to see if you can use it to play with.

advanced exercise

Another exercise would be to use that same library to see if you can create a program that display nicely on a terminal and also writes out to a text file without the terminal codes;

If you have any issues, post away, I'll help as you go along.

Upvotes: 12

KidTempo
KidTempo

Reputation: 930

Java print statements to the console can't be centered as there is no maximum width to a line.

If your console is limited to, for example, 80 chars, you could write a special logger that would pad the string with spaces.

If your string was greater than 80 chars then you would have to cut the string and print the remainder on the next line. Also, if someone else was using your app with a console with a different width (especially smaller) if would look weird.

So basically, no, there is no easy way to center the output...

Upvotes: 1

Julien Bodin
Julien Bodin

Reputation: 803

You can't. You are writing to the console which does not have a width so the center is undefined.

Upvotes: 0

Related Questions