簡體   English   中英

為什么會出現“ ArrayIndexOutOfBoundsException”錯誤?

[英]Why do I get an 'ArrayIndexOutOfBoundsException' error?

我是Java編程的新手。

有人可以通過以下代碼為我提供幫助:

 public class RandomSeq { public static void main(String[] args) { // command-line argument int N = Integer.parseInt(args[0]); // generate and print N numbers between 0 and 1 for (int i = 0; i < N; i++) { System.out.println(Math.random()); } } } 

嘗試編譯時收到以下錯誤消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

先感謝您。

[1]我使用64位Java 8(更新25)SE實現,並使用針對Java開發人員的64位Eclipse IDE(4.4.1版)。

如果運行main()而不給出參數list( String[] args ),它將args設為空。

因此,索引0不是有效索引,因為args為空。

int N =Integer.parseInt(args[0]);// this cause ArrayIndexOutOfBoundsException

如何在Eclipse中為main()設置參數? 從這里讀

這是因為args為空:

public class RandomSeq {
    public static void main(String[] args) {
        // command-line argument
        if (args.length > 0) {
            int N = Integer.parseInt(args[0]);

            // generate and print N numbers between 0 and 1
            for (int i = 0; i < N; i++) {
                System.out.println(Math.random());
            }
        }
        else {
            System.out.println("args is empty");
        }
    }
}

Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run

確保在運行配置下的“主要”選項卡下選擇了正確的項目名稱及其主要方法

這是因為您沒有傳遞任何值,所以args []為空。
使用Eclipse時,請轉到Run->Run Configuration-> Arguments ,傳遞一些值。
您的代碼運行得很好.. !!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM