Java 向后打印字符串的程序

Java program that prints a string backwards

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

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++;
    }
}

出于某种原因,它只打印了所有一个字母,我不确定为什么。

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

如:

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

减小长度值

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

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

Demo

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

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

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

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

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

您可以使用 StringBuffer Class。

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

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

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