[英]How do I pass these variables from different methods in to other methods
我正在自己學習Java,並且我正在嘗試這段代碼。
要求如下:
void setDimensions(double w, double h)
字段的Rectangle類,以及一個將其參數值分配給這些字段的void setDimensions(double w, double h)
方法。 getArea()
和double getPerimeter()
來計算並返回矩形的面積和周長,並使用mutator(“ setter”)方法void scale(double sf)
將矩形的寬度和高度乘以比例因子sf。 通過在您的類中編寫適當的toString方法來完成。
public class Rectangle { double width; double length; /** */ public void setDimensions(double width, double length) { width = 5; length = 10; } /* */ public static double getPerimeter(double width, double length) { double perimeter = 2 * (width + length); return perimeter; } /* */ public static double getArea(double width, double length) { double area = (width * length); return area; } /** * */ public void scale(double sf) { sf *= length; sf *= width; } public String toString() { System.out.println("The length is: " + length); System.out.println("The width is: " + width); getArea(width, length); getPerimeter(width, length); return "The area is:" + area; return "The perimeter is:" + perimeter; }
}
話雖如此,我對如何格式化toString方法感到困惑。 這個toString方法只是應該打印出面積,周長,sf等值嗎? 還是我應該返回某種字符串(對不起,我是新手,我並不完全了解)。另外,我不認為我的SF方法可以正常工作。 該方法應該在方法中初始化SF嗎?
謝謝
通常,toString方法是人類可讀的字符串,用於輸出對象的屬性/值。
@Override
public String toString() {
String myStr= "{length: " + getLength() + ", width: " + getWidth() +
", perimiter: " + getPerimiter() + ", area: " + getArea() + "}";
return myStr;
}
// will output something like "{length: 2, width: 3, perimiter: 10, area: 6}"
同樣,縮放方法應通過提供作為參數的因子來增加長度和寬度。
public void scale(double sf)
{
length *= sf;
width *= sf;
}
// better to create getters and setters and use these.
public void setLength(ln){
this.length = ln;
}
public double getLength(){
return this.length;
}
// same for width, then...
public void scale(double sf){
setLength(getLength()*sf);
setWidth(getWidth()*sf);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.