java - 使java输出特定数量的字符,具体取决于控制台中的输入

标签 java

我需要编写一个程序,让用户在控制台中写入 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/

相关文章:

java - 检查 future 时间(纪元毫秒)是否在当前时间(纪元毫秒)的 3 小时内

java - 无法获取对象的属性

java - url 中的非法参数异常

java - NoSuchMethodError : scala. Predef$.$conforms()Lscala/Predef$$less$冒号$less

java - 数学类、方法和随机数 (Java)

java - 如何修复 Microsoft Access 中的表(使用 SQL)中的数据未显示在我的 TableView (fxml) 上的问题?

java - 为什么 Ant 找不到 javac?

java - eclipse indigo 中的可运行 jar 创建选项

java - 创建/排序 List<X>,其值的顺序与 List<Y> 中的顺序相同

java - 在 biginteger 上使用 java 默认二进制搜索