2010-11-09 25 views
0

基本上,我基本上有一条线,它有一个尖顶在40, 如果添加2个单词是每个10个字母,每个长度留下20个空格 thouse 20个空格应该是充满点......例如 你好................................你添加点到system.out.println

堆栈溢出...........................

现在我的代码工作正常,我只是不关于如何在system.out.println中取悦这个想法,以便打印结果t控制台。

我想在使用whileloop打印一次一个点之后,在测试一次打印多少个点后应该有一些打扰的词被输入。

目前,我有这个这显然行不通

{ 
     System.out.println (word1 + ".." + word2); 

     while (wordlegnth1 + wordlegnth2 < LINELENGTH) 

     { 
      System.out.println (word1 + "." + word2); 

      wordlegnth1++; 

     } 

回答

3
final int LINE_LENGTH = 40; 

String word1 = ...; 
String word2 = ...; 

StringBuilder sb = new StringBuilder(LINE_LENGTH); 
sb.append(word1); 
for (int i = 0; i + word1.length() + word2.length() < LINE_LENGTH; i++) { 
    sb.append("."); 
} 
sb.append(word2); 

System.out.println(sb.toString()); 

注意:在使用StringBuilder的是为了避免性能下降,由于字符串不变性

1
/** 
* Formats a given string to 40 characters by prefixing it with word1 and 
* suffixing it with word2 and using dots in the middle to make length of final 
* string = 40. 
* If string will not fit in 40 characters, -1 is returned, otherwise 0 is 
* returned. 
* 
* @param word1 the first word 
* @param word2 the second word 
* @return 0 if string will fit in 40 characters, -1 otherwise 
*/ 
public static int formatString(String word1, String word2) { 
    final int LINELENGTH = 40; 

    // determine how many dots we need 
    int diff = LINELENGTH - (word1.length() + word2.length()); 

    if (diff < 0) { 
     // it's too big 
     System.out.println("string is too big to fit"); 
     return -1; 
    } 
    // add the dots 
    StringBuilder dots = new StringBuilder(); 
    for (int i = 0; i < diff; ++i) { 
     dots.append("."); 
    } 

    // build the final result 
    String result = word1 + dots.toString() + word2; 

    System.out.println(result); 

    return 0; 

} 

public static void main(String[] args) throws Throwable { 
    formatString("stack", "overflow"); 
    String str = ""; 
    for (int i = 0; i < 21; ++i) { 
     str += "a"; 
    } 
    formatString(str, str); 
} 

输出:

stack...........................overflow 
string is too big to fit 
0

为什么不喜欢的东西开始:

int lengthA = word1.length(); 
int lengthB = word2.length(); 
int required = LINE_LENGHT - (lengthA + lengthB); 

for(int i = 0; i < required; i++) 
{ 
    System.out.print("."); 
} 

它可以改进(尝试字符串非常大例如,或使用StringBuilder而不是System.out.print)。

0

Apache的公地郎添加到您的类路径和使用StringUtils.leftPad()

System.out.println(str1 + StringUtils.leftPad(str2, 40 - str1.length(), '.')); 

为什么要写做一些别人已经写+测试的方法?

+0

我猜这是功课...因此而不是依赖于某个库的学生应该搞清楚执行它所需的逻辑。 – TofuBeer 2010-11-09 21:32:36

+0

这不是问题的一部分。 – pstanton 2010-11-09 21:41:04