java - 如何避免 ArrayIndexOutOfBounds?

标签 java arrays

我正在尝试输入一个数字,并让程序创建一个该长度的新数组。然后,我将一次一个地输入数组中的所有元素。之后,我键入一个数字,程序将在数组中搜索该数字。不幸的是,我在下面编写的代码抛出了一个 ArrayIndexOutOfBoundsException。我该如何解决这个问题?

import java.io.*;
public class aw
{
    public static void main(String args [])throws IOException``
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        int z;
        boolean vince = false;
        System.out.print("Enter Element :");
        int a = Integer.parseInt(in.readLine());
        int [] jes = new int[a];

        for(z=0; z<jes.length; z++)
        {
            System.out.print("Numbers :");
            jes[z] = Integer.parseInt(in.readLine());

        }

        System.out.print("Enter search:");

        int []x = new int [100];
        x[100] = Integer.parseInt(in.readLine());

        if(jes[z] == x[100])
        {
            vince = true;
            if(vince == true)
            {
                System.out.print("Array "+jes[z]+ "Found at Index"+z); // here is my problem if i input numbers here it will out of bounds
            }
        }
    }
}

最佳答案

第一个问题是你重用了 z 而没有重置它。您的循环递增 z 直到它大于数组的最大索引 jes ,因此当您尝试重用 z 时,您使用的是超出范围的索引。当您尝试将读入值与 jes 进行比较时,我认为您缺少 for 循环这可能会重置和重用 z,但使用不同的变量来递增可能会更清楚。

第二个是您为 x 声明了一个大小为 100 的数组,并试图访问第 101 个索引(超出范围)。 int[] x = new int[100]具有 0-99 的指数。

此代码应按预期工作:

import java.io.*;
public class aw
{
    public static void main(String args []) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        boolean vince = false;
        System.out.print("Enter Element :");
        int a = Integer.parseInt(in.readLine());
        int [] jes = new int[a];

        for(int i=0; i<jes.length; i++) {
            System.out.print("Numbers :");
             jes[i] = Integer.parseInt(in.readLine());

        }

        System.out.print("Enter search:");
        int x = Integer.parseInt(in.readLine());
        for(int i=0; i < jes.length; i++) {
            if(jes[i] == x) {
                vince = true;
                break; //found the value, no need to keep iterating
            }
        }

        if(vince == true) {
            System.out.print("Array "+jes[i]+ "Found at Index"+i);
        }
    }
}

关于java - 如何避免 ArrayIndexOutOfBounds?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337826/

相关文章:

java - 使用qt通过套接字发送图像并使用java读取它

java - Amazon S3 连接返回错误请求

java - 复制外部硬盘

Python - 将数组拆分为多个数组

c++ - 由于某种原因,我的 C++ glm::vec3 数组似乎被重置为 null

java - 有没有比保留相同功能的三个嵌套 map 更好的解决方案?

java - 当项目有多个 pom xml 文件时,如何构建单独的 war 文件?

javascript - 更改 [].__proto__.constructor 和 [].constructor 差异的行为

javascript - 来自多维数组的全日历事件数据

java - 取一个字符串并将其转换为二维数组 Java