2015-04-22 104 views
1

我想知道如何檢查方法中的args.length。傳遞數組通過方法(java命令行參數)

例如:

public static void commandLineCheck (int first, int second){ 
    if (args.length==0){ 
     //do something with first and second 
    } 
} 

public static void main(String[] args) { 
    int first = Integer.parseInt(args[0]); 
    int second = Integer.parseInt(args[1]); 
    commandLineCheck(first, second); 
} 

我得到一個 「無法找到符號:ARGS」 錯誤當我這樣做。現在,我想我還需要通過args []方法。我試過這個,但它給了我一個「」錯誤。對此有沒有一個初學者友好的解決方案?

編輯:非常感謝你的快速回復傢伙!有效!

回答

0
像這樣(您需要數組的參數傳遞到您的檢查方法)

更改代碼

public static void commandLineCheck (int first, int second, String[] args){ 
    if (args.length==0){ 
     //do something with first and second 
    } 
} 

public static void main(String[] args) { 
    int first = Integer.parseInt(args[0]); 
    int second = Integer.parseInt(args[1]); 
    commandLineCheck(first, second, args); 
} 

,它會工作。但是,下面的測試(args.length==0)沒有什麼意義,因爲您已經通過在main方法內提取兩個值來假定args.length大於或等於2。因此,當你到達你的commandLineCheck方法時,這個測試將始終是錯誤的。

0

您需要將String [] args傳遞給commandLineCheck方法。這與您爲main方法聲明陣列的方式相同。

public static void commandLineCheck (String[] args){ 
    if (args.length==0){ 
     //do something with first and second 
    } 
} 

此外,你可能想要改變你的主要方法和commandLineCheck方法。

public static void commandLineCheck(String [] args) { 
    /* make sure there are arguments, check that length >= 2*/ 
    if (args.length >= 2){ 
     //do something with first and second 
     int first = Integer.parseInt(args[0]); 
     int second = Integer.parseInt(args[1]); 
    } 
} 

public static void main(String[] args) { 
    commandLineCheck(args); 
}