0

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

扫描仪接受“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);
        }
    }
}
4

5 回答 5

2

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

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

    for (int i = 0; i < s.length(); i++) {
        System.out.println(spaces + s.charAt(i));
        spaces += "  ";
    }
于 2013-08-10T05:44:53.597 回答
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. 


        }
于 2013-08-10T05:48:19.553 回答
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+" ";
    }
于 2013-08-10T05:49:08.550 回答
0

使用来自 commons-lang 的StringUtils :

int indent = 0;
for (final char c : "ZIP".toCharArray()) {
    System.out.println(StringUtils.repeat(" ", indent) + c);
    indent++;
}
于 2013-08-10T05:50:42.463 回答
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(" ");
}
于 2013-08-10T05:52:26.333 回答