我正在学习 Java 编程的第一个类,我们的作业之一是创建一个值字符串,该字符串以相反的顺序显示,并用逗号分隔。我知道我可能错过了一些非常简单的东西,但经过几个小时的尝试,我只是不知道我哪里出了问题?
我的代码可以工作,但是我不断收到此错误消息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at ip2_jolley.IP2_Jolley.main(IP2_Jolley.java:148)
Three, Two, One Java Result: 1
这是我正在使用的代码:
String[] f = {"One", "Two", "Three"};
if (f.length > 0) System.out.print (f[2]);
for (int i = 1; i < f.length; i--){
System.out.print(", " + f[i]);
}
最佳答案
在您的代码中,您从 1 开始,循环直到数组的长度,但每次都会递减 i。这有点困惑。您想要做的是从数组的末尾开始(因此f.length - 1
)并继续移动到数组的“左侧”,直到到达数组的开头。所以你想要这个:
for (int i = f.length-1; i >= 0; i--){
System.out.print(f[i]);
}
关于java - 错误消息 : Exception in thread "main" java. lang.ArrayIndexOutOfBoundsException:-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22899876/