我是java的新手,我正在尝试将我的经验从c#world移植到java这里是代码:
public class TestBasket {
private Item[] shops = {} ;
int arraysIndex=0;
public static void main(String argc[]){
TestBasket tb = new TestBasket();
try{
tb.storeItems(new Item("test", 100));
}
catch(Exception e){
System.out.println("Error");
System.out.println(e.toString());
}
}
public void storeItems(Item it){
if (arraysIndex >= shops.length){
///resizeArray(shops);
System.out.println("the count of length is" + shops.length);
cpArr(shops);
System.out.println("the count of length is" + shops.length);
}
shops[arraysIndex] = it;
arraysIndex++;
}
//this is a generic method to resize every kind of array
public Item[] cpArr(Item[] arr){
Item[] retArr = Arrays.copyOf(arr, arr.length + 10);
return retArr;
}
}
Run Code Online (Sandbox Code Playgroud)
执行程序后,我会收到以下消息:
长度是0
长度是0
错误
java.lang.ArrayIndexOutOfBoundsException:0
这意味着数组的长度仍然是零,它不应该为零.我很困惑我哪里出错了?
问候.
我得到了答案,这是我的错,我必须获得后退值,因为我没有这样做.
你没有使用以下结果:
cpArr(shops);
Run Code Online (Sandbox Code Playgroud)
这种方法的作用是创建一个新数组,当前的数组没有任何变化!所以你需要这样做:
shops = cpArr(shops);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
1040 次 |
| 最近记录: |