2013-10-24 116 views
-1
package helloworld; 
public class windspeed { 

    public static void main(String args[]) { 
     int t = Integer.parseInt(args[44]); //this is the array input for temperature 
     int v = Integer.parseInt(args[15]); //this is the array input for wind speed 
     double x = Math.pow(v, 0.16); //this is the exponent math for the end of the equation 
     if (t < 0) { 
      t = t*(-1); //this is the absolute value for temperature 
     } 
     double w = (35.74 + 0.6215*t)+((0.4275*t - 35.75)* x); //this is the actual calculation 
     if (t<=50 && v>3 && v<120) { //this is so the code runs only when the equation works 
      System.out.println(w); 
     } 
     if (t>50 || v<3 || v>120){ 
      System.out.println("The wind chill equation doesn't work with these inputs, try again."); 
     } 

    } 
} 

這給了我一個ArrayIndexOutOfBounds錯誤。無論我在[]中輸入什麼內容,都會出現錯誤...爲什麼?我該如何解決它?Java數組索引越界異常的不管數組長度

+0

什麼'System.out.println(args.length);'在控制檯中顯示? (把它作爲在main方法的第一行) – Craig

+0

好像你沒有使用ARGS正確:http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html – Radiodef

+0

添加'的System.out .println(args.length)'到頂部,並查看發生了什麼 – dognose

回答

-1

在這些線路:

int t = Integer.parseInt(args[44]); //this is the array input for temperature 
int v = Integer.parseInt(args[15]); //this is the array input for wind speed 

你說你有至少45個參數運行您的程序!在15.地點是風速而在44.是溫度。

你可能正在運行的程序與所有或與一個沒有參數。

請注意,如果您運行參數的程序:「世界你好你怎麼樣」的節目將有大小5參數數量與args[1]

0

具有args[0]helloworld原因是

int t = Integer.parseInt(args[44]);

你有45個參數嗎?

+1

你的意思是45? – Craig

+0

是克雷格,謝謝你讓我知道。 –

+0

高興地幫忙:) – Craig

-1

你現在有什麼是: - 乘坐15號命令行參數和轉換爲以整數; - 採用第44個命令行參數並將其轉換爲Integer。 你確定這是你需要的嗎?

0

這裏的問題是要在其中創建陣列的方式:

int t = Integer.parseInt(args[44]); //this is the array input for temperature 
int v = Integer.parseInt(args[15]); //this is the array input for wind speed 

args指的是傳遞給你的程序的main()方法的命令行參數。如果你試圖解析args[44]當沒有45點的參數(0索引,還記得嗎?),你最終會分配null到您的陣列。

所以,你將在以後最終是ArrayIndexOutOfBoundsException監守你不能索引一個空數組。如果你需要的是規模

  1. 數組在Java中是​​或int t[]

    int t[] = new int[44]; // please notice the brackets 
    int v[] = new int[15]; //this is the array input for wind speed 
    

    上述方法就足夠了。他們中的任何一個都可以,但括號需要在那裏。

  2. 使用Math.abs()找到絕對值。可以節省的if()
+0

'int t [] = Integer.parseInt(44);'和'int v [] = Integer.parseInt(15);'不要編譯。 .. –

+0

@DennisMeng謝謝你指出。 =) –

0
int t = Integer.parseInt(args[44]); //this is the array input for temperature 
int v = Integer.parseInt(args[15]); //this is the array input for wind speed 

argsargs爲主要方法中的命令行參數。如果不是args內有45個元素,則會拋出ArrayIndexOutOfBounds

要知道長度,請使用:

args.length 

比你可以繼續進行。希望能幫助到你。