我有这个代码从args获得平均值:
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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,我不能让它工作(没有例外它说"数组越界"),有没有办法来定义args的大小?请帮忙!
您正在尝试访问索引args.length.改变你for的想法
for (int i = 0; i < args.length; i++) // Without the = in the condition
Run Code Online (Sandbox Code Playgroud)
在任何数组中,最大可访问索引始终是array.length - 1.这就是为什么当你尝试访问数组中的args.length索引时args,它会抛出ArrayIndexOutOfBoundsException.