【发布时间】:2013-09-20 05:57:03
【问题描述】:
我正在做一个赋值,它需要一个带有字符串和 int 作为参数的方法。该方法应该用空格填充参数字符串,直到它的长度是给定的长度。例如,padString("hello", 8 应该返回 "hello___"(_ 代表三个空格)) 如果 int 大于字符串的长度,那么它会简单地返回字符串。我无法关闭程序的“填充”部分。
由于这个作业在本书的早期部分,我认为它可以用初学者的东西来完成,例如 forloops、参数和常见的字符串方法,因为我不应该使用 if/else 语句。
这是我目前拥有的——明显有缺陷的——代码:
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 (" ");
}
}
}
顺便问一下,有没有办法通过 for 循环在字符串变量上添加空格等内容?感谢您的帮助。
【问题讨论】:
标签: java string object for-loop