输出应该是数组中的每个单词用自己的行向后打印
public class Main
{
public static void main(String[] args)
{
String [] list = {"every", "nearing", "checking", "food", "stand", "value"};
String reverse = "";
int length = list.length;
for(int j=0; j<list.length; j++)
{
String word = list[j];
for ( int i = length - 1 ; i >= 0 ; i-- )
{
reverse = reverse + word.charAt(i);
}
System.out.println(reverse);
}
}
}
但我一直收到这条消息
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 5
at java.lang.String.charAt(String.java:658)
enter code here`at Main.main(Main.java:13)
最佳答案
我稍微清理了你的代码。不要依赖不会提高代码可读性的临时变量。一定要尝试使用 for-each
循环(它们提高了可读性)。应用这两点,给我们
String[] list = { "every", "nearing", "checking", "food", "stand", "value" };
for (String word : list) {
for (int i = word.length() - 1; i >= 0; i--) {
System.out.print(word.charAt(i));
}
System.out.println();
}
这是基于您的原始代码。就个人而言,我更喜欢使用StringBuilder
及其“reverse()
方法。喜欢,
for (String word : list) {
System.out.println(new StringBuilder(word).reverse());
}
或在 Java 8+ 中,使用 map
之类的
Arrays.stream(list).map(s -> new StringBuilder(s).reverse())
.forEachOrdered(System.out::println);
关于java - 在 Java 中获取 "Exception in thread "main"java.lang.StringIndexOutOfBoundsException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53027958/