我正在寻找一种在java中反转单词的方法。 这是我的代码,它发生了错误。
谁能解释一下为什么吗?
import java.util.Scanner;
public class Robot {
public static void reverse(String text) {
int leng = text.length();
int i = 0;
while (leng-i>=0){System.out.print(text.charAt(leng-i));
i++;
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type in your text: ");
String text = reader.nextLine();
System.out.print("In reverse order: ");
reverse(text);
}
}
我预计它会颠倒单词的顺序,但事实并非如此。
最佳答案
应该是
int i = 1;
否则,您将收到 StringIndexOutOfBoundsException
,因为 text.length()
永远不是有效的索引。
为了使其更短(更酷),您可能需要编写
System.out.print(text.charAt(leng - i++));
System.out.print(new StringBuilder(text).reverse());
关于java - 关于 JAVA 单词顺序反转的基本 Java 编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58063494/