[英]ArrayIndexOutOfBoundsException Need aid with a simple command-line program in Java
目標是制作一個程序,用戶在其中輸入數字作為命令行參數。 輸入的整數將與序列中該位置的斐波那契數相對應,例如數組。 錯誤是
線程“主”中的異常java.lang.ArrayIndexOutOfBoundsException:0
public class Main {
public static void main (String[] args)
{
int x = Integer.parseInt(args[0]);
System.out.println(fibonacci(x));
}
public static int fibonacci(int n) {
if(n == 0)
return 0;
else if(n <= 2)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
您錯過了傳遞命令行參數的機會,因此您在這里遇到異常:
int x = Integer.parseInt(args[0]);
您應先檢查以下參數:
if (args.length>0){
int x = Integer.parseInt(args[0]);
} else {
//print usage
}
如果使用命令行運行代碼,則需要按以下方式傳遞參數:
java <ClassName> <arg1>
以您的情況為例:
java Main 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.