簡體   English   中英

我寫了斐波那契數列的代碼,但出現錯誤ArrayIndexOutofBoundsException。 你能幫我么

[英]i wrote the code for fibonacci series but i get error ArrayIndexOutofBoundsException. can you please help me

我寫了斐波那契數列的代碼,但出現錯誤ArrayIndexOutofBoundsException 您能幫我找到此異常的來源嗎?

class Fib {
    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        System.out.println("Fibonacci Series");
        int f1, f2 = 0, f3 = 1;
        for (int i = 1; i <= num; i++) {
            System.out.print(" " + f3 + " ");
            f1 = f2;
            f2 = f3;
            f3 = f1 + f2;
        }
    }
}

您沒有向程序提供任何命令行參數,因此args是零長度的數組。 零長度數組的任何訪問都將導致ArrayIndexOutOfBoundsException

在訪問第一個元素(索引為0 )之前,請檢查args.length是否至少為1

我尚未測試您提交的代碼,但以下是一些提示:

  • 您正在執行應用程序而沒有任何參數。
  • 您應該首先檢查參數長度是否大於0。
  • 在解析輸入參數之前,請檢查它是否為數字或使用try / catch包圍解析。

我希望這有幫助。

祝好運!

暫無
暫無

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

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