I'm doing an assignment which requires a method with a string and an int as parameters. The method should pad the parameter string with spaces until its length is the given length. For instance, padString("hello", 8 should return "hello___"(the _ represents the three spaces)) If the int is higher than the length of the string, then it would simply return the string. I'm having trouble getting the "padding" part of the program down.
As this assignment is early on in the book, I assume it can be done with beginner stuff such as forloops, parameters, and common string methods as I'm not supposed to use if/else statements yet.
Here's the—obviously flawed—code that I have currently:
public class Exercise11 {
public static final String word = "congratulations";
public static final int length = 10;
public static void main(String[] args) {
padString();
}
public static String padString(String word, int length) {
if (word.length() >= length) {
return word.substring(0,length + 1);
} else {
String thing = word;
return word + addSpaces(word, length);
}
}
public static void addSpaces(String word, int length) {
for (int i = 1; i <= length-word.length(); i++) {
return (" ");
}
}
}
By the way, is there a way to add something such as spaces onto a String variable with a for loop? Thanks for the help.