Java程序向后打印字符串

标签 java string character

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

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 没有改变,并且您正在使用 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));
}

关于Java程序向后打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29592948/

相关文章:

java - 与 i++ 相比,执行强制转换操作的成本有多高?

Java arraylist 复制 - 克隆?

sql - 雪花: ListAgg data based on condition

javascript - JS/正则表达式 : Remove a substring from end of string with optional comma and spaces in front and dot behind

java - MVC : Value in dropdown menu doesn't set to selected value - remains 0

java - 对 3D 动画的 libgdx 值的疑问

python - 如何在 Python 中计算字符串的数字、字母、空格?

c - 如何从 C 中的函数返回字符数组?

unicode - 未知字符的字符代码,例如方形或问号罗布

vb.net - 在 VB.NET 中循环遍历字符串中的字符