简体   繁体   中英

System.out.println() output other thing

Here is some code I have written that I am having some trouble understanding:

public static void main(String[] args){      
    try {
        int l = 14;
        int hold[] = new int[1000];

        int list [] = new int[l];
        for(int i=0;i<=l;i++){
            list[i] = hold[i];
        }

        for(int i=0;i<8;i++){
            System.out.println(list[i]);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

I expected the output to be 8 lines of 0, but is 14 (1 line output) Based on observation, the output is depend on variable l in the code(why)? I would like to ask why problem this occur?

You go above the bound of array list, which makes exception.

Exactly here:

for(int i=0;i<=l;i++){      <=====
        list[i] = hold[i];
    }

Should be to l-1.

It's a common beginners-trap, so don't worry and always remember every array or list starts from 0 in most languages we have.

The reason why this occurs is because in line 7 of your code, you created a for loop which keeps going out of bounds of the list.

Whenever you loop through an array, remember your starting index is 0, not 1. That means your array of size 14 has elements numbered from 0 through 13 inclusive.

Your for loop goes all the way up to index 14, which does not exist in your array of size 14. To solve this, you need to stop at the last index of the loop. Which means the size of the array minus 1 (which will always give you the last index of your array).

To fix this, your code should be the following:

public static void main (String [] args) {
        try {
            int l = 14;
            int hold[] = new int[1000];

            int list [] = new int[l];
            for(int i=0;i<=l-1 ;i++){
                list[i] = hold[i];
            }

            for(int i=0;i<list.length;i++){
                System.out.println(list[i]);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM