【问题标题】:How do I print the characters of a String variable in a diagonal line?如何在对角线上打印字符串变量的字符?
【发布时间】:2015-10-18 22:51:29
【问题描述】:

如何获取String 变量并在对角线上向下打印其内容?最好使用forwhile 循环。

这是我现在的代码,它不能按预期工作:

String str = JOptionPane.showInputDialog("enter a string");

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

这会在一条向下的线上输出str,但不是对角线。我怎样才能让它看起来像这样:

E
 X
  A
   M
    P
     L
      E

【问题讨论】:

  • 不是只打印字符,而是使用print() 打印i 空格,然后使用println() 打印字符。
  • 缩进忽略了意图,我想说 ;-)

标签: java string for-loop


【解决方案1】:

只需再添加一个循环,在您的角色前添加适当数量的等于i 的空格。

       for(int i = 0; i < str.length(); i++) {
            for (int spacesCount = 0; spacesCount<i; spacesCount++){
                System.out.print(" ");
            }
            System.out.println(str.charAt(i));
        }

【讨论】:

  • 效果很好,但我只有一个问题 - 有没有办法避免在它的末尾出现 Exception in thread "main": String index out of range: 7
  • @salamander 这不会引发异常。错误在您的原始代码中 (i &lt;= str.length())。
【解决方案2】:
public class HelloWorld {

    public static void main(String[]args) {
        printDiagonal("hello");
    }
    public static void printDiagonal(String s)
    {
        String holdSpace = "";
        while (s.length() > 0)
        {
            String c = s.substring(0,1);
            if(s.length() > 0) 
            {
                s = s.substring(1);
            }
            holdSpace += " ";
            System.out.println(holdSpace + c);
        }
    }
}

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人学习
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
相关资源
最近更新 更多