我用 C++ 编写了一个简短的字符串反转程序。我决定用 Java 编写它,所以我就这样做了。然而,当我完成程序编写后,我遇到了几个错误,我试图修复但无法修复。错误之一是 ArrayOutOfBounds 异常。请帮我修复错误。 C++ 程序运行良好。下面是Java代码。请注意,我不想使用内置函数。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String word;
int i = 0;
boolean inp = true;
System.out.println("Enter one or more words to be reversed:");
word = scan.nextLine();
char wordArray[] = word.toCharArray();
while(wordArray[i]!='\0')
i++;
while(inp == true){
i--;
System.out.println(wordArray[i]);
if(i==0){
System.out.println();
break;
}
}
}
}
最佳答案
Java 字符串中没有空终止字符;他们有一个 length()
方法,您应该使用它来确定长度。
此外,while
循环会更惯用:
while (true) {
...
}
或者作为一个简单的for
循环。
关于java - 反向字符串程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8097587/