如何在Java中对角显示单词?

时间:2013-08-10 05:41:07

标签: java

我正在尝试创建一个接受单词的程序,然后显示对角字。到目前为止,我只是让它垂直显示。

扫描仪接受“zip”,然后输出:

z  
i  
p  

我如何让它像这样:

z  
  i  
    p

这是我的代码:

import java.util.Scanner;
public class exercise_4 
{
    public static void main(String [] args)
    {
        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter your words");

        String word = scan.nextLine();

        for (char ch: word.toCharArray())
        {
            System.out.println(ch);
        }
    }
}

5 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情: -

   String s = "ZIP";
    String spaces = "";

    for (int i = 0; i < s.length(); i++) {
        System.out.println(spaces + s.charAt(i));
        spaces += "  ";
    }

答案 1 :(得分:1)

你可以做到

String spaces = ""; // initialize spaces to blank first
        for (int i = 0; i < word.length(); i++) { // loop till the length of word
            spaces = spaces + "  "; //
           // increment spaces variable 
           // for first iteration, spaces = ""
           // for second iteration, spaces = " "
           // for third iteration, spaces = "  "
           // for fourth iteration, spaces = "   " and so on

            System.out.println(spaces + word.charAt(i));
           // this will just print the spaces and the character of your word. 


        }

答案 2 :(得分:0)

试试这个

Scanner scan = new Scanner(System.in);
    System.out.println("Please enter your words");
    String word = scan.nextLine();
    String i = new String();
    for (char ch : word.toCharArray()) {
        System.out.println(i+ch);
        i=i+" ";
    }

答案 3 :(得分:0)

来自commons-lang的StringUtils

int indent = 0;
for (final char c : "ZIP".toCharArray()) {
    System.out.println(StringUtils.repeat(" ", indent) + c);
    indent++;
}

答案 4 :(得分:0)

我更喜欢使用StringBuilder进行连接。

String s = "ZIP";
StringBuilder sb = new StringBuilder();

for (int i = 0; i < s.length(); i++) {
   System.out.println(sb.toString()+ s.charAt(i));
   spaces.append(" ");
}