简体   繁体   中英

Java add padding before a string BJP4 Exercise 3.17: padString

public class Practice {
    public static void main(String[] args) {
        System.out.println(padString("hi", 8));
    }

    public static String padString(String string, int length) {
        int wordLength = string.length();

        for (int space = 1; space <= length - wordLength; space++) {
             string = "." + string;
        }
        return string;
    }
}

This code works the way it is suppose to, but how? The output is ......hi (Correct) why does it not print .hi.hi.hi.hi.hi.hi (Wrong but why) I'm confused, why does the string not print out 6 times as well? The period prints 6 times but not "hi". Please can someone explain this?

Because string = "." + string; string = "." + string; inserts a single . at the beginning of string (it does not repeat string ). In fact, your code could be improved with a StringBuilder (which might also make this clearer for you). Like,

public static String padString(String string, int length) {
    int count = length - string.length();
    StringBuilder sb = new StringBuilder(string);
    for (int space = 0; space < count; space++) {
        sb.insert(0, '.');
    }
    return sb.toString();
}

1) The first time when the loop is executed string variable gets the value of .hi

2) After the first time, the loop "concatenates" the dot to .hi until the last iteration.

The purpose of "+" operator is concatenation and not to re-insert the "hi"

Hence, the output. Other thing you could do is to set a breakpoint in the code and Debug as Java Application to see what happens each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM