[英]ArrayIndexOutOfBoundsException when printing the reverse of an array
When running it in cmd it shows error: 在cmd中运行它时显示错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Reverse.main(Reverse.java:18) 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:Reverse.main(Reverse.java:18)为5
My code is 我的代码是
import java.util.*;
class Reverse
{
public static void main (String agrs[])
{
Scanner sc = new Scanner (System.in);
int a,r,s;
System.out.print("Enter Number: ");
r= sc.nextInt();
int num[]=new int[r];
for (a=0;a<r;a++)
{
System.out.print("Enter Number: "+(a+1)+":");
num[a]=sc.nextInt();
}
System.out.println("\n Displaying number in reverse order\n-----------\n");
for (a= num[a]-1;a<0;a--)
{
System.out.println(num[a]);
}
}
}
Since I am new to java, I am confused about how to fix this. 由于我是java的新手,所以我对如何解决此问题感到困惑。
Problem here: 问题在这里:
for (a= num[a]-1;a<0;a--){
System.out.println(num[a]);
}
ArrayIndexOutOfBoundsException means the array does not have an index of num[a] - 1
. ArrayIndexOutOfBoundsException表示数组没有索引num[a] - 1
。
Try this instead: 尝试以下方法:
for (a = r - 1; a >= 0; a--){
System.out.println(num[a]);
}
Or use num.length - 1
: 或者使用num.length - 1
:
for (a = num.length - 1; a >= 0; a--){
System.out.println(num[a]);
}
You solved the problem thanks to mmking's answer. 借助mmking的答案,您解决了问题。
Now let's think about how to print the reverse of an array using java 8 features. 现在,让我们考虑一下如何使用Java 8功能打印数组的逆序。
Use of numeric Stream 使用数字流
int num[] = { 5, 6, 7, 8 };
IntStream.range(1, num.length + 1).boxed()
.mapToInt(i -> num[num.length - i])
.forEach(System.out::println);
Use of Collections.reverseOrder
使用Collections.reverseOrder
Stream.of(5, 6, 7, 8).sorted(Collections.reverseOrder())
.forEach(System.out::println);
Use of descendingIterator
使用descendingIterator
Stream.of(5, 6, 7, 8).collect(Collectors.toCollection(LinkedList::new))
.descendingIterator().forEachRemaining(System.out::println);
Output 输出量
8
7
6
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.