根据控制台中的输入,使java输出特定数量的字符
我需要编写一个程序,让用户在控制台中写入3个单词,然后程序重新打印这3个单词(每行一个),但也用点(“.”)填充每行中的剩余空格,因此每行中的字符总数变为总共30个字符 例如: 输入:根据控制台中的输入,使java输出特定数量的字符,java,Java,我需要编写一个程序,让用户在控制台中写入3个单词,然后程序重新打印这3个单词(每行一个),但也用点(“.”)填充每行中的剩余空格,因此每行中的字符总数变为总共30个字符 例如: 输入: Hello Me Overflow 输出: .........................Hello ............................Me ......................Overflow 这是我目前拥有的生成错误的代码。作为作业的一部分,我得到了代码(在底部),需
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(".");
}
}
}
import java.util.*;
公共类填充点{
专用静态int LineLength=30;
公共静态void main(字符串[]arg){
String[]threeWord=新字符串[3];//定义3个位置以将字符串放置在数组“threeWord”中
扫描仪控制台=新扫描仪(System.in);
System.out.println(“输入三个字:”);
字符串wordOne=console.next();
threeWord[1]=wordOne;//将第一个单词保存到数组“threeWord”
String wordTwo=console.next();
threeWord[2]=wordTwo;//将第二个单词保存到数组“threeWord”
String wordThree=console.next();
三字[3]=wordThree;//将第三个字保存到数组“三字”
for(int i=0;i
除了索引从0
开始外,还需要在repeatChar
方法中返回点:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
公共静态字符串repeatChar(char repeatChar,int repeatTimes){
字符串结果=”;
对于(int j=0;j
您可以使用现有库进行填充
for(String temp:threeWord)
system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") );
这可能会简化您的代码数组索引从0开始
threeWord[0]、threeWord[1]、threeWord[2]
@user7很好,谢谢!)如果您只是让repeat方法构建了一个句点字符串,那就行了。但是,您调用的方法在另一个系统中打印时不返回字符串::println;当您将来提出问题时,请确保包含您从代码中获得的任何错误,并指出导致错误的行。谢谢。是否有任何方法可以保持循环的代码(使用变量I)不变,并对repeatChar
方法进行更改?我很难理解循环中方法的,
部分。我猜我不应该在我的repeatChar
方法中打印“.”?这非常有效!非常感谢。是命令字符串结果=”代码>基本上告诉Java从“零点”开始,然后是结果+=repeatChar代码>基本上每次需要添加一个点字符?Java如何知道repeatTime
的长度(基本上它如何知道循环中要进行多少次迭代)?将repeatTimes
传递给它,并在for
循环中使用repeatTimes
。这就是它的工作原理。