以金字塔形式打印字符串[关闭] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center。

7年前关闭。

我喜欢以一个字母一个字母的形式打印从用户输入的字符串。
例如-当用户输入为“字符串”时,输出应为:

     s
    s t
   s t r
  s t r i
 s t r i n
s t r i n g

我尝试了一个小程序,但是它没有以金字塔形式排列单词。该程序是

    import java.io.*;
    import java.util.Scanner;
    import java.lang.String;

    public class Mainer {
    public static void main(String args[]){
       try
       {
           Scanner sc = new Scanner(System.in);
           String s;
           int l;
           System.out.println("Enter the String : ");
           s = sc.nextLine();
           l = s.length();
           for(int i=0; i<l;i++)
           {

               for(int j=0;j<i;j++)
               {
                   System.out.printf("%c ",s.charAt(j));
               }
               System.out.printf("%c\n",s.charAt(i));
           }         

       }
       catch(Exception e)
       {
           System.err.println(e);
       }
    }
}

上面程序的输出是(当输入字符串时)
输入字符串:

s
s t
s t r
s t r i
s t r i n
s t r i n g

您能否将其安排为第一个示例?

java大神给出的解决方案

在输出字符串之前,需要将字符串长度的一半添加为字符串前面的空格数(填充)。但是每次迭代时都要减去1个空间以创建形状。

或者说另一种说法是,您将获得原始字符串的长度,并打印出未打印字符的空格数。

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

从Java到php5? [关闭] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely …

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…

从方法返回数组-Java - java

private static Coordinate[] getCircleCoordintaes() { Coordinate coordinates[] = {new Coordinate(0, 0)}; return coordinates; } 以上程序工作正常。在上面的程序中,返回的坐标数组首先初始化了数组使用这条线Coordinate coordi…

Java Swing SearchBox模型 - java

我需要使用Java Swing的搜索框,如果单击任何建议,当输入字母时它将显示来自数据库的建议,它将执行一些操作。如果有可能在Java swing中,请提供源代码提前致谢 java大神给出的解决方案 您可以使用DefaultComboBoxModel,输出将是这样。Try this在此代码中,您将找到countries数组,因此您需要从数据库中获取此数组。