How to center a print statement text?












10















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









share|improve this question























  • Why not center the graphics.drawString("Hello",x,y) ? You need applet to have good and easy stuff.

    – huseyin tugrul buyukisik
    May 18 '13 at 22:14








  • 1





    The short answer is: You can't. You have no idea what "the middle" is - you're printing to standard out.

    – Brian Roach
    May 18 '13 at 22:14






  • 1





    This question might have some useful infos for you.

    – A4L
    May 18 '13 at 22:27











  • Can you clarify what the "center" is? Where are you viewing your program's output? Can one assume that the output will always be limited to, say 80 characters? Or will it be of variable length?

    – slhck
    May 18 '13 at 22:29











  • the place where im printing this statement is a jde called dr.java

    – user2070292
    May 18 '13 at 22:30
















10















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









share|improve this question























  • Why not center the graphics.drawString("Hello",x,y) ? You need applet to have good and easy stuff.

    – huseyin tugrul buyukisik
    May 18 '13 at 22:14








  • 1





    The short answer is: You can't. You have no idea what "the middle" is - you're printing to standard out.

    – Brian Roach
    May 18 '13 at 22:14






  • 1





    This question might have some useful infos for you.

    – A4L
    May 18 '13 at 22:27











  • Can you clarify what the "center" is? Where are you viewing your program's output? Can one assume that the output will always be limited to, say 80 characters? Or will it be of variable length?

    – slhck
    May 18 '13 at 22:29











  • the place where im printing this statement is a jde called dr.java

    – user2070292
    May 18 '13 at 22:30














10












10








10


2






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









share|improve this question














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






java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 18 '13 at 22:12









user2070292user2070292

62138




62138













  • Why not center the graphics.drawString("Hello",x,y) ? You need applet to have good and easy stuff.

    – huseyin tugrul buyukisik
    May 18 '13 at 22:14








  • 1





    The short answer is: You can't. You have no idea what "the middle" is - you're printing to standard out.

    – Brian Roach
    May 18 '13 at 22:14






  • 1





    This question might have some useful infos for you.

    – A4L
    May 18 '13 at 22:27











  • Can you clarify what the "center" is? Where are you viewing your program's output? Can one assume that the output will always be limited to, say 80 characters? Or will it be of variable length?

    – slhck
    May 18 '13 at 22:29











  • the place where im printing this statement is a jde called dr.java

    – user2070292
    May 18 '13 at 22:30



















  • Why not center the graphics.drawString("Hello",x,y) ? You need applet to have good and easy stuff.

    – huseyin tugrul buyukisik
    May 18 '13 at 22:14








  • 1





    The short answer is: You can't. You have no idea what "the middle" is - you're printing to standard out.

    – Brian Roach
    May 18 '13 at 22:14






  • 1





    This question might have some useful infos for you.

    – A4L
    May 18 '13 at 22:27











  • Can you clarify what the "center" is? Where are you viewing your program's output? Can one assume that the output will always be limited to, say 80 characters? Or will it be of variable length?

    – slhck
    May 18 '13 at 22:29











  • the place where im printing this statement is a jde called dr.java

    – user2070292
    May 18 '13 at 22:30

















Why not center the graphics.drawString("Hello",x,y) ? You need applet to have good and easy stuff.

– huseyin tugrul buyukisik
May 18 '13 at 22:14







Why not center the graphics.drawString("Hello",x,y) ? You need applet to have good and easy stuff.

– huseyin tugrul buyukisik
May 18 '13 at 22:14






1




1





The short answer is: You can't. You have no idea what "the middle" is - you're printing to standard out.

– Brian Roach
May 18 '13 at 22:14





The short answer is: You can't. You have no idea what "the middle" is - you're printing to standard out.

– Brian Roach
May 18 '13 at 22:14




1




1





This question might have some useful infos for you.

– A4L
May 18 '13 at 22:27





This question might have some useful infos for you.

– A4L
May 18 '13 at 22:27













Can you clarify what the "center" is? Where are you viewing your program's output? Can one assume that the output will always be limited to, say 80 characters? Or will it be of variable length?

– slhck
May 18 '13 at 22:29





Can you clarify what the "center" is? Where are you viewing your program's output? Can one assume that the output will always be limited to, say 80 characters? Or will it be of variable length?

– slhck
May 18 '13 at 22:29













the place where im printing this statement is a jde called dr.java

– user2070292
May 18 '13 at 22:30





the place where im printing this statement is a jde called dr.java

– user2070292
May 18 '13 at 22:30












7 Answers
7






active

oldest

votes


















8














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.






share|improve this answer































    2














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






    share|improve this answer


























    • And how would he determine the length that method requires?

      – Brian Roach
      May 18 '13 at 22:25



















    1














    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...






    share|improve this answer































      1














      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






      share|improve this answer

































        1














        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.






        share|improve this answer


























        • what exactly does "%-20s" do?

          – user2070292
          May 18 '13 at 22:29






        • 2





          %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

          – Jonny Henly
          May 18 '13 at 22:54











        • It definitely works, but this can't be made dynamic, right?

          – Shreshth Kharbanda
          Jan 27 at 5:33











        • @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

          – Jonny Henly
          Jan 31 at 17:21



















        0














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






        share|improve this answer
























        • You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

          – huseyin tugrul buyukisik
          May 18 '13 at 22:15













        • This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

          – slhck
          May 18 '13 at 22:15








        • 4





          @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

          – Brian Roach
          May 18 '13 at 22:16






        • 1





          Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

          – Ahmed Masud
          May 18 '13 at 22:18








        • 1





          The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

          – Brian Roach
          May 18 '13 at 22:21





















        0














        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 |
        +----------------------+





        share|improve this answer
























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16629476%2fhow-to-center-a-print-statement-text%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          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.






          share|improve this answer




























            8














            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.






            share|improve this answer


























              8












              8








              8







              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.






              share|improve this answer













              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.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 18 '13 at 22:49









              Ahmed MasudAhmed Masud

              15.9k32539




              15.9k32539

























                  2














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






                  share|improve this answer


























                  • And how would he determine the length that method requires?

                    – Brian Roach
                    May 18 '13 at 22:25
















                  2














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






                  share|improve this answer


























                  • And how would he determine the length that method requires?

                    – Brian Roach
                    May 18 '13 at 22:25














                  2












                  2








                  2







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






                  share|improve this answer















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







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 16 '18 at 8:25

























                  answered May 18 '13 at 22:18









                  Laksitha RanasinghaLaksitha Ranasingha

                  2,8002130




                  2,8002130













                  • And how would he determine the length that method requires?

                    – Brian Roach
                    May 18 '13 at 22:25



















                  • And how would he determine the length that method requires?

                    – Brian Roach
                    May 18 '13 at 22:25

















                  And how would he determine the length that method requires?

                  – Brian Roach
                  May 18 '13 at 22:25





                  And how would he determine the length that method requires?

                  – Brian Roach
                  May 18 '13 at 22:25











                  1














                  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...






                  share|improve this answer




























                    1














                    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...






                    share|improve this answer


























                      1












                      1








                      1







                      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...






                      share|improve this answer













                      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...







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 18 '13 at 22:20









                      KidTempoKidTempo

                      715521




                      715521























                          1














                          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






                          share|improve this answer






























                            1














                            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






                            share|improve this answer




























                              1












                              1








                              1







                              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






                              share|improve this answer















                              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







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 6 '14 at 5:09

























                              answered Nov 6 '14 at 5:00









                              marcelocramarcelocra

                              1,27711728




                              1,27711728























                                  1














                                  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.






                                  share|improve this answer


























                                  • what exactly does "%-20s" do?

                                    – user2070292
                                    May 18 '13 at 22:29






                                  • 2





                                    %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

                                    – Jonny Henly
                                    May 18 '13 at 22:54











                                  • It definitely works, but this can't be made dynamic, right?

                                    – Shreshth Kharbanda
                                    Jan 27 at 5:33











                                  • @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

                                    – Jonny Henly
                                    Jan 31 at 17:21
















                                  1














                                  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.






                                  share|improve this answer


























                                  • what exactly does "%-20s" do?

                                    – user2070292
                                    May 18 '13 at 22:29






                                  • 2





                                    %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

                                    – Jonny Henly
                                    May 18 '13 at 22:54











                                  • It definitely works, but this can't be made dynamic, right?

                                    – Shreshth Kharbanda
                                    Jan 27 at 5:33











                                  • @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

                                    – Jonny Henly
                                    Jan 31 at 17:21














                                  1












                                  1








                                  1







                                  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.






                                  share|improve this answer















                                  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.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Sep 27 '18 at 14:05

























                                  answered May 18 '13 at 22:18









                                  Jonny HenlyJonny Henly

                                  3,51042040




                                  3,51042040













                                  • what exactly does "%-20s" do?

                                    – user2070292
                                    May 18 '13 at 22:29






                                  • 2





                                    %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

                                    – Jonny Henly
                                    May 18 '13 at 22:54











                                  • It definitely works, but this can't be made dynamic, right?

                                    – Shreshth Kharbanda
                                    Jan 27 at 5:33











                                  • @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

                                    – Jonny Henly
                                    Jan 31 at 17:21



















                                  • what exactly does "%-20s" do?

                                    – user2070292
                                    May 18 '13 at 22:29






                                  • 2





                                    %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

                                    – Jonny Henly
                                    May 18 '13 at 22:54











                                  • It definitely works, but this can't be made dynamic, right?

                                    – Shreshth Kharbanda
                                    Jan 27 at 5:33











                                  • @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

                                    – Jonny Henly
                                    Jan 31 at 17:21

















                                  what exactly does "%-20s" do?

                                  – user2070292
                                  May 18 '13 at 22:29





                                  what exactly does "%-20s" do?

                                  – user2070292
                                  May 18 '13 at 22:29




                                  2




                                  2





                                  %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

                                  – Jonny Henly
                                  May 18 '13 at 22:54





                                  %s is telling the String's format method that there is a String variable that goes where the %s is. The -20 between the % and s tells the String's format method the number of spaces that String should be offset by, a negative value offsets spaces to the left, a positive value offsets spaces to the right.

                                  – Jonny Henly
                                  May 18 '13 at 22:54













                                  It definitely works, but this can't be made dynamic, right?

                                  – Shreshth Kharbanda
                                  Jan 27 at 5:33





                                  It definitely works, but this can't be made dynamic, right?

                                  – Shreshth Kharbanda
                                  Jan 27 at 5:33













                                  @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

                                  – Jonny Henly
                                  Jan 31 at 17:21





                                  @ShreshthKharbanda it can be made dynamic if the IDE or terminal / command prompt that you're outputting to has an accessible variable (i.e. environment variable) that holds the output console's number of columns.

                                  – Jonny Henly
                                  Jan 31 at 17:21











                                  0














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






                                  share|improve this answer
























                                  • You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

                                    – huseyin tugrul buyukisik
                                    May 18 '13 at 22:15













                                  • This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

                                    – slhck
                                    May 18 '13 at 22:15








                                  • 4





                                    @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

                                    – Brian Roach
                                    May 18 '13 at 22:16






                                  • 1





                                    Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

                                    – Ahmed Masud
                                    May 18 '13 at 22:18








                                  • 1





                                    The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

                                    – Brian Roach
                                    May 18 '13 at 22:21


















                                  0














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






                                  share|improve this answer
























                                  • You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

                                    – huseyin tugrul buyukisik
                                    May 18 '13 at 22:15













                                  • This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

                                    – slhck
                                    May 18 '13 at 22:15








                                  • 4





                                    @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

                                    – Brian Roach
                                    May 18 '13 at 22:16






                                  • 1





                                    Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

                                    – Ahmed Masud
                                    May 18 '13 at 22:18








                                  • 1





                                    The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

                                    – Brian Roach
                                    May 18 '13 at 22:21
















                                  0












                                  0








                                  0







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






                                  share|improve this answer













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







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered May 18 '13 at 22:14









                                  Julien BodinJulien Bodin

                                  737318




                                  737318













                                  • You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

                                    – huseyin tugrul buyukisik
                                    May 18 '13 at 22:15













                                  • This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

                                    – slhck
                                    May 18 '13 at 22:15








                                  • 4





                                    @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

                                    – Brian Roach
                                    May 18 '13 at 22:16






                                  • 1





                                    Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

                                    – Ahmed Masud
                                    May 18 '13 at 22:18








                                  • 1





                                    The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

                                    – Brian Roach
                                    May 18 '13 at 22:21





















                                  • You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

                                    – huseyin tugrul buyukisik
                                    May 18 '13 at 22:15













                                  • This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

                                    – slhck
                                    May 18 '13 at 22:15








                                  • 4





                                    @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

                                    – Brian Roach
                                    May 18 '13 at 22:16






                                  • 1





                                    Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

                                    – Ahmed Masud
                                    May 18 '13 at 22:18








                                  • 1





                                    The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

                                    – Brian Roach
                                    May 18 '13 at 22:21



















                                  You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

                                  – huseyin tugrul buyukisik
                                  May 18 '13 at 22:15







                                  You can have a formula to add how many spaces befor and after. You need a method separately to be clear.

                                  – huseyin tugrul buyukisik
                                  May 18 '13 at 22:15















                                  This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

                                  – slhck
                                  May 18 '13 at 22:15







                                  This is not entirely true. If you knew the console width, or restricted it to some value you could easily center it.

                                  – slhck
                                  May 18 '13 at 22:15






                                  4




                                  4





                                  @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

                                  – Brian Roach
                                  May 18 '13 at 22:16





                                  @slhck - except there's no guarantee there even is a console. stdout is just ... stdout

                                  – Brian Roach
                                  May 18 '13 at 22:16




                                  1




                                  1





                                  Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

                                  – Ahmed Masud
                                  May 18 '13 at 22:18







                                  Okay rather than confusing a newbie with redirect stdio and stderr and all sorts of other pieces, there is merit in just thinking about it as a complete beginner and help them walk through the issue. It is actually possible to determine whether a console is attached to a tty which supports terminal emulation and thus you can do this.

                                  – Ahmed Masud
                                  May 18 '13 at 22:18






                                  1




                                  1





                                  The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

                                  – Brian Roach
                                  May 18 '13 at 22:21







                                  The point is, this answer is correct. Programmatically there is no way to determine "the middle" when you're talking about stdout. I'm quite sure the OP could figure out printing some spaces to move the text to the right.

                                  – Brian Roach
                                  May 18 '13 at 22:21













                                  0














                                  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 |
                                  +----------------------+





                                  share|improve this answer




























                                    0














                                    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 |
                                    +----------------------+





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      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 |
                                      +----------------------+





                                      share|improve this answer













                                      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 |
                                      +----------------------+






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 14 '18 at 9:07









                                      Thomas DecauxThomas Decaux

                                      13.4k25864




                                      13.4k25864






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16629476%2fhow-to-center-a-print-statement-text%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Florida Star v. B. J. F.

                                          Danny Elfman

                                          Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues