Ran across a blind spot in trying to figure this out. I want to pad a string with n characters to the left (at the beginning) of the String. This is the code I have come up with padRight and padLeft but when I go run the program it doesn't do any thing. I know I need another class like maybe a StringTester but I don't know how to go about it. Could someone please help me out with this one?

public class StringUtils
{
      public static String padRight(String s, int n)
      {
        return String.format("%1$-" + n + "s", s);
      }

      public static String padLeft(String s, int n)
      {
        return String.format("%1$" + n + "s", s);
      }
}

Run what program? Where's your main method?
To use those methods you need to call them and print the result, eg
System.out.println(StringUtils.padRight("Hello", 12));

James I am new to Java Programming. Sometimes I am afraid to ask a question because my level of intelligence about Java is very low. Do I System.out.println in the same program or do I have to create a new class? Thank you very much in advance.

  1. Everyone here was a beginner once. There's no such thing as a dumb question. Don't be afraid!

  2. You don't need a new class. You could put a main method in that class to contain code thqat will test those methods

Thank you James, sometimes I feel like I am out of my league here. But here is what I have come up with.

public class StringUtils
{
    public static void main(String args[]) {

         System.out.println(padLeft("Trying to learn Java Programming.s.s.", 95) + "*");
         System.out.println(padRight("On the down low.n.n.", 50) + "&");
        }

     public static String padLeft(String s, int n)
     {
     return String.format("%1$" + n + "s", s);
     }

     public static String padRight(String s, int n)
     {
     return String.format("%1$-" + n + "s", s);
     }
}

Which gave me the ouput of:

                                                          Trying to learn Java Programming.s.s.*
On the down low.n.n.                              &

I hope this is what I am suppose to demonstrate. Thank you again.

Yes, that does it.
Here's a slightly different test code that shows the results more clearly:

System.out.println("|" + padLeft("Hello", 12) + "|");
System.out.println("|" + padRight("Hello", 12) + "|");

Please give that a try - the | characters before and after make it esy to see where the padding is

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.