gpt4 book ai didi

java - 实例变量没有在方法中被调用

转载 作者:行者123 更新时间:2023-12-02 12:22:30 24 4
gpt4 key购买 nike

如果输入正确,我想在运行时调用区域实例变量以在Setter方法中显示其值。我正在使用 TriangleTester 来测试 Triangle 类。我只想根据所需的输出计算三角形的面积和周长

enter image description here

Triangle.java

import java.util.Scanner;
class Triangle
{
private int a,b,c; //sides of the triangle
private double s,area; //and 's' for the Heron's Formula
private int peri;
String type=new String();

Triangle()
{
System.out.println("*****A Java Application To Determine Triangle and Comupute*****");
setter();
}



public void inputAndDetermine()
{
if(((a+b)>c)&&((a+c)>b)&&((b+c)>a))
{
determineType();
calculatePerimeter();
calculateArea();
displayResult();
}
else
{
System.out.println("The input doesn't describe a triangle");
}
}

public void determineType()
{
if((a==b)&&(a==c))
{
type="Equilateral triangle";
}
else if((a==b)||(b==c)||(a==c))
{
type="Isoceles triangle";
}
else
{
type="Scalene triangle";
}
}

public void calculatePerimeter()
{
peri=a+b+c;
}

public strictfp void calculateArea()
{
s=(a+b+c)/2;
area=(Math.sqrt((s*(s-a)*(s-b)*(s-c))));
}

public void displayResult()
{
System.out.println("\t Summary of Computing Triangle Perimeters & Areas \t");
System.out.println("----------------------------------------------------------");
System.out.println("\t Sides(a,b,c) \t Perimeter \t Area \t Type \t");
System.out.println("----------------------------------------------------------");
System.out.println("\t " + a + " " + b + " " + c + "\t " + peri + "\t " + area + "\t" + type );
System.out.println("");
System.out.println("");
System.out.println("Bar Chart Of Number of Triangle Constructed");
}

public void setter()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the length of 1st side of Triangle 1 : ");
this.a=keyboard.nextInt();
System.out.print("Enter the length of 1st side of Triangle 1 : ");
this.b=keyboard.nextInt();
System.out.print("Enter the length of 1st side of Triangle 1 : ");
this.c=keyboard.nextInt();
System.out.println("The Triangle perimeter and area are :");
System.out.println("\t \t" + peri + " unit, " + area + " units. " + type );
System.out.println("-----------------------------------------------------------");
}

}

TriangleTester.java

class TriangleTester
{
public static void main(String [] ar)
{
Triangle tri = new Triangle();
tri.inputAndDetermine();
}
}

这是我得到的输出

Output Of the program

最佳答案

将setter方法代码更改为

...
this.c=keyboard.nextInt();
// add these two lines
calculatePerimeter();
calculateArea();

System.out.println("The Triangle perimeter and area are :");
System.out.println("\t \t" + peri + " unit, " + area + " units. " + type );
System.out.println("-----------------------------------------------------------");

但这似乎毫无意义。

关于java - 实例变量没有在方法中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45666117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com