我在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]);
}
您以int i = 1开始循环,然后在每个循环中将其减少1,这将导致i小于0。
除了使用之外int i = 1
,您可能还想使用int i = f.length
编辑
您想要的可能是这样的:
String[] f = {"One", "Two", "Three","Four","Five"};
//start at f.length - 1, continue until there is no item left
for (int i = f.length-1; i >= 0; i--){
//print current item
System.out.print(f[i]);
//if it is not the last item, print separator
if(i>0){
System.out.print(", ");
}
}
}
编辑有一些解释
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句