简体   繁体   English

为什么这段 Java 代码会抛出异常?

[英]Why does this Java code throw an exception?

I am new with java.我是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)线程“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.你会得到一个ArrayOutOfBoundsIndexException ,因为循环是无止境的,但索引总是增加。

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.一个总是小于numlength ,因此它永远循环,每次递增i直到i大于数组大小。 At which point you'll try to do this此时你会尝试这样做

num[i] ...

And i will be out of bounds, throwing the exception. i会越界,抛出异常。

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 .这就是您收到ArrayOutOfBoundsIndexException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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