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