我在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++;
}
非常感谢任何帮助!
答案 0 :(得分:2)
取决于数组的容量,语句
theWords[g] = theWords[z]
将在第一次执行循环时失败,因为z =数组的长度(数组中的最后一个索引是length - 1)。在旁注中,在循环中,您最初设置
g = howMany - 1
然后递减它,所以g&lt; howMany将永远是真的...你将有一个无限循环。当g或z低于0时,此无限循环也可能导致索引超出范围异常。
答案 1 :(得分:1)
如果在执行函数之前howMany == capacity - 1
,则会出现问题。
会发生什么:你进入if的第一个分支(//添加单词)然后你增加howMany
,然后你成为howMany = capacity
然后你分配z = howMany
并访问一个外面的数组它的界限:theWords[g] = theWords[z];
。
另一件事是你没有增加capacity
变量,它必须是capacity+=10
。
这是我的变体:
import java.util.Arrays;
import java.util.Random;
public class OrderedArray{
int howMany = 0;
String[] theWords = new String[10];
public void addWord(String newWord) {
//don't accept nulls
if(newWord == null) {
return;
}
//if length is reached increase the array
if(howMany >= theWords.length - 1) {
theWords = Arrays.copyOf(theWords, theWords.length+10);
}
//go through existing words and add newWord if it is less then met value
boolean isAdded = false;
for(int idx = 0; idx < howMany && theWords[idx] != null; idx++){
if(newWord.compareTo(theWords[idx]) < 0){
isAdded = true;
String valToShift = theWords[idx];
theWords[idx] = newWord;
//copy all values after the met index
for(int shIdx = idx+1; shIdx <= howMany && shIdx < theWords.length; shIdx++){
String tmp = theWords[shIdx];
theWords[shIdx] = valToShift;
valToShift = tmp;
}
break;
}
}
//if a value was not added then add it
if(!isAdded){
theWords[howMany] = newWord;
}
++howMany;
}
public String toString(){
StringBuffer sb = new StringBuffer("howMany:");
sb.append(howMany);
for(int idx = 0; idx < howMany; idx++){
sb.append(",");
sb.append(theWords[idx]);
}
return sb.toString();
}
public static void main(String[] args){
OrderedArray m = new OrderedArray();
Random r = new Random(System.currentTimeMillis());
for(int i = 0; i < 210; i++){
m.addWord(Math.abs(r.nextInt())+ "");
}
System.out.println(m);
OrderedArray m1 = new OrderedArray();
m1.addWord("c");
m1.addWord("d");
m1.addWord("a");
m1.addWord("cd");
System.out.println(m1);
}
}