【问题标题】:Java program that prints a string backwards向后打印字符串的 Java 程序
【发布时间】:2015-04-12 18:24:05
【问题描述】:

我正在尝试编写一个程序,该程序接受一个字符串,将其分解为字符,然后将每个字符向后打印。我有点明白问题是什么,我只是不知道如何解决它。这是我的代码:

public static void main(String[] args) {
    //takes a string and prints all the letters backwards all on one line

    String fruit = "apple";
    backwards(fruit);
    }

public static void backwards(String theFruit) {
    int length = theFruit.length() - 1;
    int counter = 0;
    while(length > counter) {
        char theCharacter = theFruit.charAt(length);
        System.out.println(theCharacter);
        counter++;
    }
}

由于某种原因,它只打印一个字母,我不知道为什么。

【问题讨论】:

  • 长度永远不会改变,你总是在length输出字符

标签: java string character


【解决方案1】:

问题是 length 没有改变,而您正在使用 println 语句的长度。

不要在循环结束时添加到计数器,而是从长度中减去。然后,您应该更改您的 while 以检查是 >= 计数器:

while (length >= counter)
{
    System.out.println(theFruit.charAt(length));
    length--;
}

您也可以更改循环并改用 for 循环:

for (int i = length; i >= 0; i--)
{
    System.out.println(theFruit.charAt(i));
}

【讨论】:

    【解决方案2】:

    我认为最简单的方法是使用StringBuilder 类。

    public static void backwards(String theFruit) {
        return new StringBuilder(theFruit).reverse().toString();
    }
    

    【讨论】:

      【解决方案3】:

      减少while 循环中的length。并且不要增加counter 变量。

      作为:

      while(length >= counter) {
          char theCharacter = theFruit.charAt(length);
          System.out.println(theCharacter);
          length--;
      }
      

      【讨论】:

        【解决方案4】:

        减小长度的值

        while(length >= counter) {
                char theCharacter = theFruit.charAt(length);
                System.out.println(theCharacter);
                length--;
        }
        

        使用您的方法,您每次都打印最后一个字符,因为 length 值从未改变

        Demo

        【讨论】:

          【解决方案5】:

          你可以使用 StringBuffer 类。

          public static void main(String[] args) {
              StringBuffer fruit = new StringBuffer("apple");
              System.ouyt.println(fruit.reverse());
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-03-01
            • 1970-01-01
            • 2013-10-01
            • 2021-11-29
            • 1970-01-01
            • 2015-06-19
            • 1970-01-01
            • 2020-11-09
            相关资源
            最近更新 更多