Q:

How to pad a string with padding lengths inside an array?

Lets say I have an array of ints such as [2,3,5,6,7] and I have a simple string like "name". How can I loop through the array and pad with every value. Supposed something like this:
Output:
    "  name" //2 spaces
    "   name" //3 spaces
    "     name" // 5 spaces and so on..

Here's what I have tried so far:
    int[] arr = [2,3,4,5,6,7];
    String s = "name";
    for(int i = 0; i < arr.length; i++){ 
     String x = Integer.toString(i);
     System.out.println(String.format("%" + x + "s", s));
    }

However, it gives me java.util.FormatFlagsConversionMismatchException at the print statement. What's the best approach to solve this?

A:

There is an indent() method from the latest java12 release. It exactly fits your case:
int[] arr = new int[]{2, 3, 4, 5, 6, 7};
String s = "name";
for (int item : arr) {
    System.out.print(s.indent(item));
}

A:

Your String.format is just a bit wrong, try below
int[] pads = new int[]{2,3,5,7};
String str = "name";
for (int length: pads) {
  System.out.println(String.format("%1$" + (length + str.length()) + "s", str));
}

