2017-07-16 38 views
0

我試圖做我的第一種方法。 我無法將周邊顯示爲String。我想知道爲什麼會發生這種情況。我的代碼裏面可能還有其他問題,但是外圍不輸出是現在讓我困擾的問題。我想知道爲什麼當我得到字符串輸出在那麼結束周長不被計算並放在字符串

以下是我的代碼。

public class Polygon { 

    public Polygon() { 
     int numSides = 4; 
     double SideLength = 5.0; 
     double xCoord = 0.0; 
     double yCoord = 0.0; 
     double apothem = 5.0; 
     double perimeter = 20.0; 
    } 

    private int numSides = 2; 
    private double SideLength = 2; 
    private double xCoord; 
    private double yCoord; 
    private double apothem; 
    private double perimeter; 
    private double area; 

    public Polygon(int numsides, double sideLength, double xcoord, double ycoord, double Apothem, double Perimeter) { 
     SideLength = sideLength; 
     numSides = numsides; 
     xCoord = xcoord; 
     yCoord = ycoord; 
     apothem = Apothem; 
     perimeter = Perimeter; 
    } 

    public int getnumsides() { 
     return numSides; 
    } 

    public double getSideLength() { 
     return SideLength; 
    } 

    public double getxcoord() { 
     return xCoord; 
    } 

    public double getycoord() { 
     return yCoord; 
    } 

    public double getApothem() { 
     return apothem; 
    } 

    public double getPerimeter() { 
     return numSides * SideLength; 
    } 

    public void setsideLength(double ssideLength){ 
     SideLength = ssideLength; 
    } 

    public void setnumsides(int snumsides){ 
     numSides = snumsides; 
    } 

    public void setxcoord(double sxcoord){ 
     xCoord = sxcoord; 
    } 

    public void setycoord(int sycoord){ 
     yCoord = sycoord; 
    } 

    public void setApothem(int sApothem){ 
     apothem = sApothem; 
    } 

    public void setPerimeter(int sPerimeter){ 
     perimeter = sPerimeter; 
    } 

    public String toString() { 
     String str = numSides + " is the number of sides the polygon has and " + SideLength + " is how long the sides are. "+ xCoord + " is how long the x coordinate is and " + yCoord + " is how long the y coordinate is. " + apothem + " is the apothem of the polygon and " + perimeter + " is the perimeter of the polygon."; 
     return str; 
    } 

    public void getArea() { 
     area = .5 * apothem * perimeter; 

    } 
} 
+0

*我想知道爲什麼會發生這種情況*而「this」會是...? – shmosel

+0

['this''](https://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java)是你的問題的原因。 –

+0

請不要用大寫字母開頭變量名。 –

回答

0

您再次在Polygon()構造函數中定義相同的字段變量,因爲您已經將它們定義爲私有類成員,所以這不是必需的。這是在打印toString()方法時將某些值設置爲默認值的原因。

你的多邊形()構造函數應該是這樣的:

public Polygon() { 
     numSides = 4; 
     SideLength = 5.0; 
     xCoord = 0.0; 
     yCoord = 0.0; 
     apothem = 5.0; 
     perimeter = 20.0; 
    } 
0

你是什麼意思的「周邊不輸出」嗎?

可能這是你想達到的目的嗎?

public static void main(String[] args){ 
     Polygon p = new Polygon(); 
     double perimeter = p.getPerimeter(); 
     System.out.println("Perimeter is " + perimeter); 
    } 
相關問題