简体   繁体   English

为什么在类中定义数组大小时会出现ArrayIndexOutOfBounds异常?

[英]Why am I getting an ArrayIndexOutOfBounds exception when array size defined in class?

For my project, a user must define the size of an array, and I created a set method to do this. 对于我的项目,用户必须定义​​数组的大小,并且我创建了set方法来执行此操作。 The variable being changed is the class variable, arraySize . 要更改的变量是类变量arraySize But, when someone sets the array size, and I try adding an array, I receive an indexoutofbounds error. 但是,当有人设置数组大小并尝试添加数组时,我收到indexoutofbounds错误。

Here's the snippet of code 这是代码片段

    //Size of the array
private int arraySize;
//initializes elemnt count of array
private int arrayElementCount;

//Gets count of SID in array
public int getSIDArrayCount() {

    //returns private variable
    return arrayElementCount;
}

//Sets SID Array
public void setArraySize(int setArraySize) {
    //Array size int
    //checks array if array size is greater than 0
    if (setArraySize > 0) {
        //sets array size
           //SIDArray
         arraySize = setArraySize;
    }

}

//SIDArray
private String[] SIDArray = new String[arraySize];

EDIT: I can't initialize the array in the 'setArraySize' method because I need an accessor method for the array. 编辑:我无法在'setArraySize'方法中初始化数组,因为我需要该数组的访问器方法。

here's the rest of the class: 这是课程的其余部分:

/*

* To change this license header, choose License Headers in Project Properties. *要更改此许可证标题,请在“项目属性”中选择“许可证标题”。 * To change this template file, choose Tools | *要更改此模板文件,请选择工具| Templates * and open the template in the editor. 模板*,然后在编辑器中打开模板。 */ package com.ahellhound.pkg202sidproject; * /包com.ahellhound.pkg202sidproject;

import java.util.Arrays; 导入java.util.Arrays; import java.util.regex.Pattern; 导入java.util.regex.Pattern;

/** * * @author Colby Leclerc */ public class SIDArrayTest { / ** * * @author Colby Leclerc * /公共类SIDArrayTest {

//Size of the array
private int arraySize;
//initializes elemnt count of array
private int arrayElementCount;

//Gets count of SID in array
public int getSIDArrayCount() {

    //returns private variable
    return arrayElementCount;
}

//Sets SID Array
public void setArraySize(int setArraySize) {
    //Array size int
    //checks array if array size is greater than 0
    if (setArraySize > 0) {
        //sets array size
           //SIDArray
         arraySize = setArraySize;
    }

}

//SIDArray
private String[] SIDArray = new String[arraySize];
//Gets SID Array
public String[] getSIDArray() {

    //returns array
    return SIDArray;
}

//Validates SID; returns true if SID entry is valid
public boolean validateSID(String SIDEntry) {
    //checks if sid entry is 7, and if starts with s
    if (SIDEntry.length() != 7) {
        //retuns false
        return false;

    }

    //checks if SIDEntry begins with 'S'
    if (!SIDEntry.matches("[sS]\\d{6}")) {

        //returns false
        return false;
    }
    //returns true
    return true;
}

//Adds SID to the Array
public void addSID(String SIDEntry) {

    //checks if SID is valid
    if (validateSID(SIDEntry)) {
        //Adds sid to array
        SIDArray[arrayElementCount] = SIDEntry;
        //increases array size by one
        arrayElementCount++;

    } else {

        System.out.println("test failed 2");
    }

}

//Gets SID array and returns all entrys to strings 
public String getSIDArrayString() {
    //Gets array and converts to string
    String SIDArrayString = Arrays.toString(SIDArray);
    //returns array string
    return SIDArrayString;

}

} }

I am truly stumped at how to set the array size, when I've created a class variable for it, while having the array a 'get'-able method. 当我为它创建了一个类变量,同时又使数组具有“可获取”的方法时,我真的为如何设置数组大小而感到困惑。

You are instantiating the array before calling your setArraySize-method, thus it gets size of 0. 您在调用setArraySize方法之前实例化数组,因此其大小为0。

//SIDArray
private String[] SIDArray = new String[arraySize];

As the SIDArray variable is in the scope of the class, it gets instantiated as soon as an object of the class is created. 由于SIDArray变量在类的范围内,因此在创建该类的对象后立即对其进行实例化。 Because of this, it uses the arraySize varible, which is uninstantiated at this point(and defaults to 0 in case of an int). 正因为如此,它使用ARRAYSIZE varible,这是在这一点非实例(和默认为0在一个int的情况下)。

To fix this, simply instantiate the array after calling setArraySize() . 要解决此问题,只需在调用setArraySize()之后实例化数组即可。

Here is some code to clarify what I meant in the comments. 这是一些代码来澄清我在注释中的含义。

public class A {
    /* In your code, you instantiate the array at this point, in the scope of the class, while arraySize is still uninitialized */
    String[] array; /* uninitialized, defaults to null */
    int arraySize; /* uninitialized, defaults to 0 */

    /* Simple accessor method for the array */
    public String[] getArray() {
        return array;
    }

    public int getArraySize() {
        return arraySize;
    }


    public void setArraySize(int size) {
        this.arraySize = size;
    }

    public void createArray() {
        array = new String[arraySize];
    }
}

You have to initialize the array variable after you set the new size. 设置新大小后,必须初始化数组变量。 Change your method to: 将您的方法更改为:

//Sets SID Array
public void setArraySize(int setArraySize) {
    //Array size int
    //checks array if array size is greater than 0
    if (setArraySize > 0) {
        //sets array size
        //SIDArray
        arraySize = setArraySize;
        SIDArray = new String[arraySize];
    }
}

The problem is that you are instantiating an array with a fixed size (0). 问题是您要实例化一个具有固定大小(0)的数组。 That's not necessarily bad... the real problem is that in you setArraySize(int setArraySize) method, you update your arraySize variable, but the array is never aware of this call!!! 并不一定很糟糕……真正的问题是,在您的setArraySize(int setArraySize)方法中,您更新了arraySize变量,但数组从未意识到此调用!!! You should use something like 您应该使用类似

SIDArray = new String[arraySize];

But even if you do this, resizing your array will destroy all its previous contents... just be aware of this. 但是即使执行此操作,调整数组大小也会破坏其所有先前的内容...请注意这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我收到ArrayIndexOutOfBounds异常? - Why I am getting ArrayIndexOutOfBounds exception? 使用String.split时,我不断收到“ ArrayIndexOutOfBounds”异常 - I keep getting a “ArrayIndexOutOfBounds” Exception when using String.split 为什么我会收到 Class Cast Exception? - Why am I getting a Class Cast Exception? 为什么我得到Class not found异常 - why I am getting Class not found exception 为什么我会获得类强制转换异常? - Why am I getting a class cast exception? 使用MillerUpdatingRegression类时ArrayIndexOutOfBounds异常 - ArrayIndexOutOfBounds Exception When Using MillerUpdatingRegression Class 我得到一个ArrayIndexOutOfBounds异常,我不知道为什么。 有人可以解释一下吗? - I'm getting an ArrayIndexOutOfBounds Exception and I don't know why. Can someone shed some light? 为什么会出现这个ArrayIndexOutOfBounds异常? - Why is this ArrayIndexOutOfBounds exception occurring? 当超类默认构造函数具有'throws'子句时,为什么我会得到未报告的异常? - Why am I getting unreported exception when the super class default constructor has a 'throws' clause? 为什么在解析行时出现数组索引超出界限异常错误? - Why am I getting an Array Index Out Of Bounds Exception error when parsing lines?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM