编写长方形类,计算面积及周长。创建两个对象,输出它们的面积及周长。 public class Rectangle{ private int width; //字段,宽,类中的变量,分配内存 private int height; //字段,高 public Rectangle() {width = 0; height = 0;} public Rectangle(int width, int height) throws Exception { setWidth((1) ); setHeight((2) ); } public(3) getWidth() { return width; } public void setWidth(int width) throws Exception { if (width <0) { throw new Exception("宽不能小于0"); } this.width =(4); } public(5)getHeight() { return height; } public void setHeight(int height) throws Exception { if (height <0) { throw new Exception("高不能小于0"); } this.height =(6) ; } public(7)Area() { //方法,计算面积 return width * height; } public (8)Perimeter() { return 2 * (width + height); }} class Program //测试类{ public static void main(String[] args) { try { //可能出现异常的代码 Rectangle rect1 = new Rectangle(); rect1.setWidth(5); rect1.setHeight(4); System.out.printf("宽为%d\n",rect1.getWidth()); System.out.printf("面积为%d,周长为%d\n", rect1.Area(), rect1.Perimeter()); } catch (Exception(9) ) { System.out.println(e.getMessage()); } try { Rectangle rect2 = new Rectangle(-7, 6); System.out.printf("面积为%d,周长为%d\n", rect2.Area(), rect2.Perimeter()); } catch (Exception (10) ) { System.out.println(e.getMessage()); } }}
查看答案
程序填空题:(1)创建时间类,它包含的三个成员变量hour、minute、second,编写TimePeriod方法,用于计算零点时刻到当前时间的时间间隔(秒)。(2)创建实例,并按6个数位hh:mm:ss(2个表示小时,2个表示分钟、2个表示秒)输出相关信息,如:03:24:33 或 14:05:45。计算并显示对象与零点时刻的时间间隔。public class Timer{ private int hour; private int minute; private int second; public int getHour() { (1); } public void setHour(int hour) throws Exception { if (hour < 0(2) hour >= 24) { throw new Exception("输入的小时不合理"); } else { (3); } } public int getMinute() {(4); } public void setMinute(int minute) throws Exception { if (minute >= 0 && minute < 60) {(5); } else { throw new Exception("输入的分钟不合理"); } } public int getSecond() {(6) ; } public void setSecond(int second) throws Exception { if (second < 0 || second >= 60) { throw new Exception("输入的秒不合理"); } else {(7); } } public(8) (int hh,int mm,int ss) throws Exception { setHour(hh); setMinute(mm); setSecond(ss); }(9) timePeriod(){return hour * 3600 + minute * 60 + second; }}public class Program{ public static void main(String[] args) { try { Timer time1 = new Timer(22, 6, 15); System.out.printf("%d:%d:%d\n" , ____); System.out.println("零点时刻到当前时间的时间间隔:" + ____); }catch(Exception e) { System.out.println(); } }}
重载的方法需要通过形式参数列表中参数的哪些形式来区分( )
A. 参数的个数和参数的顺序
B. 参数的数据类型和参数的顺序
C. 参数的个数、参数的数据类型和参数的顺序
D. 参数的个数、参数的数据类型
以下不是 Java 中 this 关键字的作用的是( )
A. 使用它调用父类的方法
B. 使用它调用本类的属性
C. 使用它调用构造方法
D. 使用它表示当前对象
按照 Javabean 规范来定义的 Person 类,成员变量的修饰符必须是( )
A. public
B. protected
C. default
D. private