代码之家  ›  专栏  ›  技术社区  ›  WoeIs

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

  •  0
  • WoeIs  · 技术社区  · 6 年前

    例子:

    Hello 
    Me 
    Overflow
    

    输出:

    .........................Hello
    ............................Me
    ......................Overflow
    

    这是我目前拥有的生成错误的代码。我已经得到了代码(在底部)作为我的任务的一部分,需要写的 repeatChar

    我做的第一件事是在代码中添加以下命令,以便将3个单词保存到数组中 threeWord

    threeWord[1] = wordOne;
    threeWord[2] = wordTwo;
    threeWord[3] = wordThree;
    

    重复字符 ,我决定使用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(".");
            }
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   xingbin    6 年前

    0 ,您需要返回 repeatChar

    public static String repeatChar(char repeatChar, int repeatTimes) {
        String result = "";
        for(int j = 0; j < repeatTimes; j++) {
            result += repeatChar;
        }
        return result;
    }
    
        2
  •  0
  •   rahul shetty    6 年前

    可以使用现有库进行填充

    for(String temp:threeWord) 
      system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") ); 
    

    这可能会简化您的代码