【发布时间】:2013-12-12 23:19:46
【问题描述】:
我正在编写一个课程来练习我的数据结构(特别是队列),我遇到了一些很奇怪的东西。我在类上将一个变量(int)初始化为零,然后尝试使用该变量将项目放入数组中。当我运行程序时,我得到了奇怪的输出。
public class QueueTest {
public static int[] myArr = new int[10];
static int currIndex = 0; ///// This variable is set to ZERO, used to keep track of where I am in the queue
public static void main(String[] args) {
printArray(); // print initial array
Queue(1); // Add integer to list
Queue(2);
Queue(3);
Queue(4);
printArray(); // print resulting array
}
// place at end of queue
public static void Queue(int number){
if(currIndex >= QueueTest.myArr.length-1)
resize();
QueueTest.myArr[currIndex] = number;
currIndex++;
}
// print the array
public static void printArray(){
for(int index : QueueTest.myArr){
System.out.print(QueueTest.myArr[index]);
}
System.out.println("");
}
public static void resize(){} //to-do
public boolean leftShift(){} //to-do
public void findCurrentIndex(){} //to-do
} // end of class
当我运行这个程序时,我得到以下输出:
0000000000
2340111111
但如果我将 currIndex 的值更改为 1,那么一切都很好地添加到数组中,只是从第二个位置开始。
0000000000
0123400000
谁能解释为什么会这样?
【问题讨论】: