Java toString()方法覆盖

时间:2017-10-05 00:15:03

标签: oop printing tostring

这两个课程我正在制作方形物品,为明天的考试做准备。 S1使用默认值创建,S2通过非默认值创建。由于某种原因,它将打印出除Side之外的所有值为0.请帮助。

public class SquareRunner{
public static void main(String[] args)
{
    Square S1 = new Square();
    Square S2 = new Square(4);
    System.out.println(S1.toString());
    System.out.println(S2.toString());
}
}

import java.lang.Math;

public class Square
{

private int s, a, p;
private double d;
public Square()
{
    s = 1;
}
public Square(int side)
{
    s = side;
}
public int getSide()
{
    return s;
}
public int getArea()
{
    a = s * s;
    return a;
}
public double getDiagonal()
{
    double d;
    d = Math.sqrt(Math.pow(s,2) + Math.pow(s,2));
    return d;
}
public int getPerimeter()
{
    p = 4 * s;
    return p;
}
public String toString()
{
    return "Side: " + s + " Perimeter: " + p + " Area: " + a + " Diagonal: " 
+ d;
}
}

1 个答案:

答案 0 :(得分:0)

试试这个

public String toString()
{
    return "Side: " + s + " Perimeter: " + this.getPerimeter() + " Area: " + this.getArea() + " Diagonal: " 
    + this.getDiagonal();
}

如果要打印周边,区域和对角线,则必须计算要打印的值。

如果你想在SquareRunner课程中打印出来,那么你可以这样做

public class SquareRunner{
public static void main(String[] args)
   {
     Square S1 = new Square();
     Square S2 = new Square(4);

     System.out.println(S1.getArea());
     ...
     ...

 }

}