Java树程序

时间:2014-02-07 01:10:10

标签: java tree substring

我需要使用Java创建一个树程序。我无法做到这一点并且没有想法。它应该使用for循环和子字符串。以下是“示例”字符串的示例:

          S
         SAS
        SAMAS
       SAMPMAS
      SAMPLPMAS
     SAMPLELPMAS
          S
          A
          M
          P 
          L
          E

这是我到目前为止所得到的:

    Scanner input = new Scanner(System.in);

    String userWord, reverse = "";
    int size;

    System.out.print("Enter a word that is less than or equal to 10 characters: ");
    userWord = input.next();

    userWord = userWord.toUpperCase();

    size = userWord.length()-1;

    for (int i = 1; i <= userWord.length() + 1; i++) {
        System.out.print(userWord.substring(0, i));
        System.out.println(userWord.substring(0,i-1));
    }

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

public static void main (String[] args) throws java.lang.Exception
{
    Scanner input = new Scanner(System.in);

    String userWord, reverse = "";
    int size;
    StringBuilder padding = new StringBuilder();

    System.out.print("Enter a word that is less than or equal to 10 characters: ");
    userWord = input.next();

    userWord = userWord.toUpperCase();
    reverse = new StringBuffer(userWord).reverse().toString();
    size = userWord.length();

    for(int i = 0; i < size; i++){
        padding.append(" ");
    }

    for (int i = 1; i <= size; i++) {
        System.out.print(padding.substring(0, size-i));
        System.out.print(userWord.substring(0, i));
        if(i > 1){
            System.out.println(reverse.substring(size+1-i, size));  //2 >= i  
        }else{
            System.out.println("");
        }
    }
    String pad = padding.substring(0, size-1).toString();
    for(int i = 0; i < size; i++){
        System.out.println(pad + userWord.charAt(i));
    }
}

答案 1 :(得分:0)

您目前正在使用一个for循环。你需要两个。第一个将通过col然后行

for (int x = 1; x <= input; x++)
{
    for (int y = 0; y < x; y++)
    {
        System.out.print( // enter what you need here);
    }
    System.out.println();
}

这有什么意义吗?如果您还有问题,请告诉我