作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要编写一个程序,让用户在控制台中写入 3 个单词,然后程序重新打印这 3 个单词(每行一个),同时用点(“.”)填充每行中的剩余空格。这样每行的字符总数就变成了 30 个字符。
示例:
输入:
Hello
Me
Overflow
输出:
.........................Hello
............................Me
......................Overflow
这是我当前生成错误的代码。作为作业的一部分,我已获得代码(位于底部),并且需要编写 repeatChar
方法才能使其工作。
我做的第一件事是在代码中添加以下命令,以便将 3 个单词保存到数组 thirdWord
中。
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
开始之外,您还需要在repeatChar
方法中返回点:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
关于java - 使java输出特定数量的字符,具体取决于控制台中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52540080/
我是一名优秀的程序员,十分优秀!