2014-04-09 15 views
2

我正在將優化建立到用Java編寫的JPEG編碼器中。要做我的基準,我想將原始代碼和優化代碼提取到分離的jar中。每個jar都需要兩個參數。第一個是文件名,第二個是重複壓縮jpeg的secound。使用多個參數運行Jar文件

public static void main(String[] args) { 
    String filepath = args[0]; 
    try { 
     int times = Integer.getInteger(args[1]); 
     runBenchmark(filepath, times); 
    } catch(IOException | NumberFormatException ioe) { 
     System.out.println("Your arguments are Wrong! Use the follow order!"); 
     System.out.println("1. Argument must be the filename of the image."); 
     System.out.println("2. Argument must be a number to repeat the compression."); 
    } 
} 

這是我的主要,女巫處理我的參數。我無法在IntellJ上運行參數。即使我將它編譯成一個罐子,我也無法通過我的arg2。 enter image description here

我在intellj中通過配置傳遞了兩個參數,我得到一個NullPointerException。所以我試圖弄清楚我的java是否可以接受兩個參數。我在vim中編寫了一個簡單的主體,並編譯了兩個參數並運行。我在intellj的一個新項目中重複了這一點。 enter image description here 這是行得通的。但爲什麼?

+0

堆棧跟蹤是難以辨認的,代碼也是如此。你可以插入問題作爲文本,請問? – fge

+0

我發現了錯誤。我寫它作爲答案 – DenniJensen

回答

2

您必須檢查參數是否爲int。 使用Integer.parseInt()和try-catch塊通知用戶是否發生故障。

int times = 0; 
try { 
    times = Integer.parseInt(args[1]); 
} catch (Exception e) { 
    System.out.println("failure with a parameter"); 
} 
+0

啊,你是對的謝謝 – DenniJensen

2

我將方法更改爲Integer.parseInt(字符串),現在它工作。它是Integer.getInt()它。我以爲我現在有2. arg,因爲我得到了NullPointerException。 現在它可以使用這段代碼。

public static void main(String[] args) { 
    try { 
     String filepath = args[0]; 
     int times = Integer.parseInt(args[1]); 
     runBenchmark(filepath, times); 
    } catch (NumberFormatException nfe) { 
     System.out.println("2. Arg must be an number"); 
    } catch (IOException ioe) { 
     System.out.println("File not found."); 
    } catch(Exception e) { 
     System.out.println("Your arguments are Wrong! Use the follow order!"); 
     System.out.println("1. Argument must be the filename of the image."); 
     System.out.println("2. Argument must be a number to repeat the compression."); 
    } 
}