简单的Java程序......执行错误。 [英] Simple Java program ...Exeption Error.
问题描述
您好,
我是初学者,刚刚开始进行java编程,通过练习我在三角区域示例中遇到了一个错误,无法解决。我尝试了一切,但我没有得到它。任何人都可以告诉我为什么这个错误会出现在以下程序中。
Hello,
I beginner and just started java programming and by doing its practice I got an error in the Example of Area of Triangle which couldn't solved out. I tried everything but I don't get it. Can anybody tell me why this error comes in following program.
/*Program to calculate area of a triangle when three sides are passed as input .*/
class Area
{
public static void main(String args[])
{
int s,sum=0,n;
double area;
n=args.length;
int []a=new int [n]; //Declaration of array to define three sides of a triangle.
for(int i=0;i<=n;i++)
{
if(n<=3)
{
a[i]=Integer.parseInt(args[i]);
sum=sum+a[i];
}
else
{
System.out.println("You Should Enter Only Three Values");
break;
}
}
if(n<=3)
{
s=sum/2;
area=Math.sqrt(s*(s-a[1])*(s-a[2])*(s-a[3]));
System.out.println("Area = "+area);
}
}
}
之后,我使用了javac编译器:
> javac area.java
> java area 3 5 6
之后出现以下错误。
>线程中的异常主java.lang.ArrayIndexOutOfBoundsException:3在Area.main< Area.java:14>
谢谢。
And after that, I used javac compiler:
>javac area.java
>java area 3 5 6
After That the following error comes.
>" Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Area.main<Area.java:14>
Thanks.
推荐答案
除了谢尔盖的回答,这部分代码也被打破了:
In addition to Sergey's answer, this part of code is broken too:
if(n< = 3)
{
s = sum / 2;
area = Math.sqrt(s *(sa [1])*(sa [2])*(sa [3]));
System.out.println(Area =+ area);
}
if(n<=3)
{
s=sum/2;
area=Math.sqrt(s*(s-a[1])*(s-a[2])*(s-a[3]));
System.out.println("Area = "+area);
}
例如,如果 n = 2
那么如果
条件评估为为真
并执行代码块,但都是 a [2]
和 a [3]
不存在。
For instance, if n=2
then the if
condition evaluates to true
and code block is executed, but both a[2]
and a[3]
don't exist.
最大i
,args [i]
不存在,因为用户没有提供这么多参数。
这是因为你的错误:
For maximumi
,args[i]
does not exist, because the user did not provide so many arguments.
It happened because of your bug:
for(int i=0;i<=n;i++)
可以通过以下方式修复:
Can be fixed by writing:
for (int i=0; i<n; i++)
我解决了。感谢您的帮助。
编辑的程序是,
I solved it. Thanks to help.
The Edited Program is,
/*Program to calculate area of a triangle when three sides are passed as input .*/
class Area
{
public static void main(String args[])
{
int s,sum=0,n,ss,m=1;
double area;
n=args.length;
int []a=new int [n]; //Declaration of array to define three sides of a triangle.
for(int i=0;i<n;i++)
{
if(n==3)
{
a[i]=Integer.parseInt(args[i]);
}
else
{
System.out.println("Please Enter Only Three Values");
break;
}
sum=sum+a[i];
}
if(n==3)
{
s=sum/2;
for(int i=0;i<n;i++)
{
ss=(s-a[i]); //ss Assigns s-a[1] to s-a[3] separately
m=m*ss; //Passing value of ss to m
}
area=Math.sqrt(s*m);
System.out.println("Area of Triangle = "+area);
}
}
}
这篇关于简单的Java程序......执行错误。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!