gpt4 book ai didi

java - 程序反转数组中的数字

转载 作者:行者123 更新时间:2023-12-01 16:55:36 26 4
gpt4 key购买 nike

当我尝试以下代码时,它给出了正确的答案。但是当我尝试使用a.length时,它会抛出ArrayIndexOutOfBoundsException。如何使我的代码使用a.length

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] a;

int n = sc.nextInt();
a = new int[n];

for(int i = 0; i <= a.length; i++) {
a[i] = sc.nextInt();
}

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

最佳答案

a 中索引 a.length 处没有元素,因为 a 的索引范围是从 0 到(a.length - 1)。由于没有索引,因此会抛出异常。

关于java - 程序反转数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33303608/

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