2011-09-12 11 views
1
public class TestSample { 
    public static void main(String[] args) { 
     System.out.print("Hi, "); 
     System.out.print(args[0]); 
     System.out.println(". How are you?"); 
    } 
} 

私はこのプログラムをコンパイルするとき、私はこのエラーを取得:例外 "メイン" java.lang.ArrayIndexOutOfBoundsException:0

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


また、なぜ私はargsを持つことができませんこれは、このようなint配列受け入れる:いいえので

public static void main(int[] args) { 

答えて

8

1は、ArrayIndexOutOfBoundsException:args.length == 0のでargs[0]が外側にあるため、0

は、それがスローされました配列は有効なインデックスの範囲(learn more about arrays)です。

args.length>0にチェックを付けて修正してください。あなた自身は、コマンドライン引数としてint[]に引数を解析する必要があります

intとして

public class TestSample { 
    public static void main(String[] args) { 
     System.out.print("Hi, "); 
     System.out.print(args.length>0 ? args[0] : " I don't know who you are"); 
     System.out.println(". How are you?"); 
    } 
} 

2.コマンドライン引数のみをString[]として渡されます。これを行うには、Integer.parseInt()を使用しますが、解析が正常に行われるように例外処理が必要です(learn more about exceptions)。 Ashkanの答えはこれを行う方法を示しています。

4
  1. にエラーが発生していますプログラムの開始時に引数が追加されました。
  2. intが必要な場合は、(JVMによる)呼び出されたメインメソッドのシグニチャがpublic static void main(String[] args)であり、public static void main(int[] args)でないため、引数から解析する必要があります。 http://download.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.htmlから

    :あなたの質問の後半部分に関してで

5

Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to an int:

int firstArg; 
if (args.length > 0) { 
    try { 
     firstArg = Integer.parseInt(args[0]); 
    } catch (NumberFormatException e) { 
     System.err.println("Argument must be an integer"); 
     System.exit(1); 
    } 
} 
関連する問題