【发布时间】:2014-02-15 16:06:24
【问题描述】:
对于我的项目,用户必须定义数组的大小,我创建了一个 set 方法来执行此操作。被改变的变量是类变量,arraySize。但是,当有人设置数组大小时,我尝试添加一个数组,我收到 indexoutofbounds 错误。
这是代码的sn-p
//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”方法中初始化数组,因为我需要数组的访问器方法。
这是课程的其余部分:
/*
* 要更改此许可标头,请在项目属性中选择许可标头。 * 要更改此模板文件,请选择工具 |模板 * 并在编辑器中打开模板。 */ 包 com.ahellhound.pkg202sidproject;
导入 java.util.Arrays; 导入 java.util.regex.Pattern;
/** * * @作者科尔比勒克莱尔 */ 公共类 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 方法时,我真的不知道如何设置数组大小。
【问题讨论】:
标签: java arrays class variables