我有这段代码可以从参数中获取平均值:
public class Mariamne
{
public static void main(String[] args)
{
System.out.print("\n");
try
{
int sum = 0;
float prom = 0;
for (int i = 0; i<=args.length; i++)
{
int a = Integer.parseInt(args[i]);
sum = a + sum;
prom = prom + 1;
}
System.out.println(sum/prom);
}
catch(Exception e)
{
System.out.println("Error.");
}
}
}
出于某种原因,我无法让它工作(除非它说“数组越界”),有没有办法定义参数的大小?请帮忙!
最佳答案
您正在尝试访问索引args.length
。将您的 for
更改为此
for (int i = 0; i < args.length; i++) // Without the = in the condition
在任何数组中,最大可访问索引始终为array.length - 1
。这就是为什么当您尝试访问 args
数组中的 args.length
索引时,它会抛出 ArrayIndexOutOfBoundsException
。
关于java - 参数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406652/