【问题标题】:Java initial values and array access basic understanding - unusual outputJava初值和数组访问基本理解——异常输出
【发布时间】: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

谁能解释为什么会这样?

【问题讨论】:

    标签: java arrays queue


    【解决方案1】:

    你的打印方式不对:

    for(int index : QueueTest.myArr){
        System.out.print(QueueTest.myArr[index]);
    }
    

    这是for each loop,因此您得到的不是索引而是数组的实际值。所以你想这样做:

    for(int value: QueueTest.myArr){
        System.out.print(value);
    }
    

    或常规用于:

    for(int i = 0; i < QueueTest.myArr.length; i++){
        System.out.print(QueueTest.myArr[i]);
    }
    

    【讨论】:

    • 呸!我知道这是我忽略的东西。非常感谢!
    【解决方案2】:

    你的打印方法不好。还要为您的代码使用适当的缩进,这样可以使其更具可读性。

    改变

    // print the array      
        public static void printArray(){
            for(int index : QueueTest.myArr){
                System.out.print(QueueTest.myArr[index]);
            }
            System.out.println("");
        }
    

         // print the array      
        public static void printArray(){
            for(int index : QueueTest.myArr){
                System.out.print(index);
            }
            System.out.println("");
        }
    

    【讨论】:

    • 如果 OP 这样做了,那么方法 Queue 将无法在其数组中添加任何 int
    猜你喜欢
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多