對於我的項目,用戶必須定義一個數組的大小,並且我創建了一個集合方法來做到這一點。被更改的變量是類變量,arraySize。但是,當有人設置數組大小,並嘗試添加數組時,我收到一個indexoutofbounds錯誤。當在類中定義數組大小時,爲什麼會得到ArrayIndexOutOfBounds異常?
這裏的代碼段的
//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];
編輯: ,因爲我需要爲陣列的訪問方法,我不能初始化在「setArraySize」法陣。
這裏是班上的其他同學:
/*
*要改變這種許可證頭,選擇在項目屬性許可頭。 *要更改此模板文件,請選擇工具|模板 *並在編輯器中打開模板。 */ package com.ahellhound.pkg202sidproject;
進口java.util.Arrays中; import java.util.regex.Pattern;
/** * * @author科爾比勒克萊爾 */ 公共類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;
}
}
我如何設置數組的大小,當我真正難倒我們爲它創建了一個類變量,同時讓這個數組成爲一個'get'-able方法。
這個問題是,我需要一個數組的訪問器方法,如果該數組在方法中初始化,我不能擁有該方法。 – Colby
你可以有一個數組的訪問方法,無論它在哪裏初始化 – Zavior
訪問方法就像這樣簡單:public String [] getArray(){return yourArray; } – Zavior