简体   繁体   中英

Why does this Java code throw an exception?

I am new with java. I having some exception while running my code:

import java.util.Random;

public class Example {
    public static void main(String[] args) {
        Random r = new Random();
        int[] num= new int[5];      

        for (int i= 0; 1<num.length; i++)
        {
            num[i]= r.nextInt(100)+1;
            System.out.println(num[i]);
        }
    }
}

It gives me the following exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Example.main(Example.java:13)

Why am I getting this exception?

Firstly, you should always copy and paste the exception text, to save us trying to guess which type of exception it is or where it's happening

You'll be getting an ArrayOutOfBoundsIndexException , because the loop is endless yet the index always increments.

for (int i= 0; 1<num.length; i++)

One is always less than the length of num so it loops for ever, incrementing i each time until i is larger than the array size. At which point you'll try to do this

num[i] ...

And i will be out of bounds, throwing the exception.

import java.util.Random;

public class test {
public static void main(String[] args) {

    Random r = new Random();
    int[] num = new int[5];

    for (int i = 0; i < num.length; i++) {
        num[i] = r.nextInt(100) + 1;
        System.out.println(num[i]);
    }

}
}

This is how a loop works:

for (initialization; termination; increment) {
    statement(s)
} 

When the termination expression evaluates to false, the loop terminates. In your case the loop never terminates. That is why you are getting an ArrayOutOfBoundsIndexException .

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