gpt4 book ai didi

java - ArayIndexOutOfBoundsException 不起作用

转载 作者:行者123 更新时间:2023-12-01 11:15:09 25 4
gpt4 key购买 nike

我的代码有问题:

import java.io.*;
import java.util.*;
public class goTooFar {
public static void main(String[] a){

int i =4;
int[] ar = new int[i];
int n = i;
Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of an array: ");
try {
n = sc.nextInt();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Now you have gone too far");
}


System.out.println("Enter " + n + " elements of an array: ");
for (i = 0; i <= n; i++) {
try {
ar[i] = sc.nextInt();
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("Now you have gone too far");
}
System.out.println("Output Numbers: ");
for (i = 0; i <= n; i++) {
System.out.println(ar[i]);
}
}
}
}

我有这样的输入:

> Enter the size of an array: 
7

> Enter 7 elements of an array:
1 4 2 5 3 9 0 7

但是,事实是这样的:

>Output Numbers: 
1
0
0
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at goTooFar.main(goTooFar.java:31)

我可以做什么来解决这个问题?有人能帮我吗?多谢。 :)

最佳答案

将数组的长度初始化为 4:

int i =4;
int[] ar = new int[i];

因此,当您输入较长的数组长度时,您会收到 ArrayIndexOutOfBoundsException。

您需要在从用户处获取长度后创建数组:

System.out.println("Enter " + n + " elements of an array: ");
ar = new int[n]; // initialize a new array
for(i = 0; i < n; i++){ // n is not a valid index for an array of length n

同时更改另一个循环的范围

    for(i = 0; i <= n; i++){
System.out.println(ar[i]);
}

    for(i = 0; i < n; i++){
System.out.println(ar[i]);
}

关于java - ArayIndexOutOfBoundsException 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31917936/

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