我已经编写了以下 java 代码,我在其中获得0
了 A 三角形的面积。这种错误输出的原因是什么?
package methodoverrideoverload;
import java.io.*;
import java.util.*;
class Figure_Area {
int dima;
int dimb;
Figure_Area()
{
}
Figure_Area(int i, int j)
{
dima=i;
dimb=j;
}
void cal_area()
{
System.out.println("Area is undefined!!");
}
}
class Figure_Area_Tri extends Figure_Area {
Figure_Area_Tri(int i, int j)
{
super(i,j);
}
void cal_area()
{
System.out.println("The area of the Triangle is "+((1/2)*dima*dimb));
}
}
class Figure_Area_Rec extends Figure_Area {
Figure_Area_Rec(int i, int j)
{
super(i,j);
}
void cal_area()
{
System.out.println("The area of the Rectangle is "+ dima*dimb);
}
}
class Figure_Area_Cir extends Figure_Area {
double pi=3.14;
Figure_Area_Cir(int i)
{
super.dima=i;
}
void cal_area()
{
System.out.println("The area of the Circle is "+ (pi*dima*dima));
}
}
class findArea {
public static void main(String args[]) throws IOException
{
System.out.println("<<-MENU-->>");
System.out.println("Enter the figure you want to know the area of->");
System.out.println("Press 1 for Triangle");
System.out.println("Press 2 for Rectangle");
System.out.println("Press 3 for Circle");
System.out.println("Press 4 to Exit");
System.out.println("Enter your choice->");
Scanner sc=new Scanner(System.in);
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter Height->");
int h=sc.nextInt();
System.out.println("Enter Base->");
int b=sc.nextInt();
Figure_Area_Tri tri=new Figure_Area_Tri(h,b);
tri.cal_area();
break;
case 2:
System.out.println("Enter Length->");
int len=sc.nextInt();
System.out.println("Enter Breadth->");
int bre=sc.nextInt();
Figure_Area_Rec rec=new Figure_Area_Rec(len,bre);
rec.cal_area();
break;
case 3:
System.out.println("Enter Radius->");
int rad=sc.nextInt();
Figure_Area_Cir cir=new Figure_Area_Cir(rad);
cir.cal_area();
break;
case 4:
break;
default:
System.out.println("Sorry! Invalid Choice");
}
}
}
我在调试模式下检查了代码,发现 和 的值dima
被dimb
设置为输入值,但不知何故,面积函数很可能无法给出正确的结果。