2013-10-24 113 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 

比你可以继续进行。希望能帮助到你。