gpt4 book ai didi

java - 打印数组的反转时出现 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 04:39:46 27 4
gpt4 key购买 nike

在cmd中运行它时显示错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Reverse.main(Reverse.java:18)

我的代码是

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]);
}
}
}

由于我是java新手,我对如何解决这个问题感到困惑。

最佳答案

这里的问题:

for (a= num[a]-1;a<0;a--){
System.out.println(num[a]);
}

ArrayIndexOutOfBoundsException 表示数组没有索引 num[a] - 1

试试这个:

for (a = r - 1; a >= 0; a--){
System.out.println(num[a]);
}

或者使用num.length - 1:

for (a = num.length - 1; a >= 0; a--){
System.out.println(num[a]);
}

关于java - 打印数组的反转时出现 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30306674/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com