我的 comp 182 课程中有一个项目,我们正在研究矢量,但我坚持制作“有序矢量”。当我尝试运行它时,我得到一个 ArrayOutofBounds 错误。
(“howMany”变量是数组“theWords”中字符串大小的计数,
代码从另一个类运行,该类读取一个包含 10 个单词的输入文件,使用此“addWord”方法添加单词从文件到“theWords”数组。)
这是我到目前为止的代码:
[顺便说一句,我们不允许只使用“数组”方法“compareTo”]
public void addWord(String newWord) {
//adds in words
if (howMany < theWords.length) {
theWords[howMany]= newWord;
howMany++;
}
else {
String t [] = new String[capacity+10];
for (int i=0; i <capacity; i++){
t[i] = theWords[i];
}
theWords = t;
theWords[howMany] = newWord;
howMany++;
}
//ordering words
for(int g = howMany - 1, z = howMany ; g < howMany; g--, z--) {
if(newWord.compareTo(theWords[g]) < 0) {
theWords[g] = theWords[z];
theWords[g] = newWord;
}
else
newWord = theWords[z];
}
howMany++;
}
任何帮助深表感谢!