第十java上机作业
第七章上级作业 7.1 public class Rectangle { double width=1; double height=1; String color=“white“; public Rectangle(){} public Rectangle(double width,double height,String color) { this.width=width; this.height=height; this.color=color; } public void setwidth(double width) { this.width=width; } public void setcolor(String color) { this.color=color; } public double getwidth() { return width; } public double getheight() { return height; } public double getArea() { return width*height; } public double getAPerimeter() { return 2*(width+height); } }class Test{ public static void main(String[] args) { Rectangle r1=new Rectangle(4,40,“red“);Rectangle r2=new Rectangle(3.5,35.9,“red“); r1.getArea(); r1.getAPerimeter(); r2.getArea(); r2.getAPerimeter(); System.out.println(r1.getArea()); System.out.println(r1.getAPerimeter()); System.out.println(r2.getArea()); System.out.println(r2.getAPerimeter()); } } 输出结果: 160.0 88.0 125.64999999999999 78.87.1 public class Rectangle { private double width = 1; private double height = 1; private String color = “white“; public static void main(String[] args) { Rectangle r1 = new Rectangle(4,40); r1.setColor(“red“); Rectangle r2 = new Rectangle(3.5,35.9); r2.setColor(“red“); System.out.println(r1.toString()); System.out.println(r2.toString()); } public Rectangle(){ this(1.0,1.0); } public Rectangle(double width,double height){ this.width = width; this.height = height; color = “white“; } public double getWidth() { return width; }public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getArea(){ return width*height; } public double getPerimeter(){ return (width + height)*2; } public String toString(){ String output = ““; output = “ 矩形的属性:\n\t 宽 “ + width + “\n\t 高:“ + height +“\n\t 颜色: “ + color + “\n\t 面积:“ + getArea() + “\n\t 周长:“ + getPerimeter(); return output; } } 输出结果为: 矩形的属性: 宽 4.0 高:40.0 颜色:red 面积:160.0 周长:88.0 矩形的属性: 宽 3.5 高:35.9 颜色:red面积:125.64999999999999 周长:78.8