我需要编写一个程序,让用户在控制台中写3个字,然后该程序重新打印这3个字(每行一个),但还要在每行中用点(“。”)填充剩余的空格。因此每行中的字符总数总计为30个字符。
示例:
输入:
Hello
Me
Overflow
输出:
.........................Hello
............................Me
......................Overflow
这是我当前拥有的生成错误的代码。作为分配的一部分,我已经获得了代码(在底部),并且需要编写repeatChar
方法以使其起作用。
我要做的第一件事是在代码中添加以下命令,以将3个单词保存到数组threeWord
中。
threeWord[1] = wordOne;
threeWord[2] = wordTwo;
threeWord[3] = wordThree;
接下来,我不得不编写方法repeatChar
,我决定使用一个for循环使其在每行中重复点,但是我很难使它适合其余部分代码。任何指导将不胜感激,谢谢。
import java.util.*;
public class FillDots {
private static int LineLength = 30;
public static void main(String[] arg) {
String[] threeWord = new String [3]; // Defines 3 locations to place strings in the array "threeWord"
Scanner console = new Scanner(System.in);
System.out.println("Type in three words:");
String wordOne = console.next();
threeWord[1] = wordOne; // Saves first word to array "threeWord"
String wordTwo = console.next();
threeWord[2] = wordTwo; // Saves second word to array "threeWord"
String wordThree = console.next();
threeWord[3] = wordThree; // Saves third word to array "threeWord"
for(int i = 0; i < threeWord.length; i++) {
System.out.println(repeatChar('.', LineLength - threeWord[i].length()) + threeWord[i]);
}
}
public static String repeatChar(String LineLength) {
for(int j = 0; j < LineLength; j++) {
System.out.print(".");
}
}
}
答案 0 :(得分:1)
除了索引从0
开始,您还需要在repeatChar
方法中返回点:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
答案 1 :(得分:0)
您可以使用现有的库进行填充
for(String temp:threeWord)
system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") );
这可能会简化您的代码