1
定義IShape接口,包含兩個方法:
·getArea(求面積方法):沒有參數,返回double類型值;
·getPerimeter(求周長方法):沒有參數,返回double類型值。
定義IDiagArea接口,繼承IShape接口,新增方法:·
getDiagonal(求對角線方法):沒有參數,返回double類型值。
定義MyRectangle(長方形類),實現IShape接口,並添加以下內容:
屬性:長、寬,double類型
構造方法:兩個參數,根據參數的值爲屬性賦值。
output方法:調用成員方法計算並輸出長方形的相關信息(長、寬、面積、周長)。
定義MySquare(正方形類),繼承MyRectangle類,實現IDiagArea接口,並添加以下內容:
構造方法:1個參數,調用父類的構造方法把長、寬設置爲相等(即邊長),爲參數的值。
重寫output方法:調用成員方法計算並輸出長方形的相關信息(邊長、面積、周長、對角線長度)(開根號可調用Math.sqrt(double a)的方法)
定義測試類Demo,編寫main方法,新建MyRectangle、MySquare對象,並分別調用它們的output方法。
代碼
package game;
public class Java上機作業5月15日_1 {
public static void main(String[] args) {
MyRectangle myRectangle = new MyRectangle(3, 2);
myRectangle.output();
MySquare mSquare = new MySquare(2);
mSquare.output();
}
}
interface IShape{
double getArea();
double getPerimeter();
}
interface IDiagArea extends IShape{
double getDiagonal();
}
class MyRectangle implements IShape{
double length,width;
public MyRectangle(double length, double width) {
super();
this.length = length;
this.width = width;
}
public double getArea() { return length * width; }
public double getPerimeter() { return 2 * ( length + width ); }
void output() {
System.out.println("長:" + length);
System.out.println("寬:" + width);
System.out.println("面積:" + this.getArea());
System.out.println("周長:" + this.getPerimeter());
}
}
class MySquare extends MyRectangle implements IDiagArea{
public MySquare(double index) { super(index, index); }
public double getDiagonal() { return Math.sqrt( 2 * Math.pow(length, 2) ); }
void output() {
System.out.println("長:" + length);
System.out.println("寬:" + width);
System.out.println("面積:" + this.getArea());
System.out.println("周長:" + this.getPerimeter());
System.out.println("對角線:" + this.getDiagonal());
}
}
2
定義MyException(自定義異常類),繼承Exception
類構造方法:無參,調用父類Exception的一個參數的構造方法,設置參數字符串爲“該數是偶數,不合法!”。
testNumber方法:無參,沒有返回值。
方法內隨機產生一個小於100的整數,並判斷其是否爲偶數,如果是,則拋出自定義異常MyException,否則輸出其值。(該方法不捕獲異常)。
生成隨機數:import java.util.Random;
//引入隨機類……Random r=new Random();
//生成隨機類對象int n=r.nextInt(100);
//隨機生成0~99的整數
定義測試類ExceptionDemo,編寫main方法:
建立MyException類對象,調用testNumber方法,使用try-catch-finally捕獲程序產生的異常並輸出異常信息,而且保證在無論有沒有產生異常程序結束時能輸出提示信息:
“=======程序運行結束!=========”
代碼
package game;
import java.util.Random;
public class Java上機作業5月15日_2 {
public static void main(String[] args) {
MyException exception = new MyException();
try {
exception.testNumber();
}catch (MyException e) {
e.printStackTrace();
}finally {
System.out.println("=======程序運行結束!=========");
}
}
}
class MyException extends Exception{
public MyException() {super("該數是偶數,不合法!");}
public void testNumber() throws MyException {
Random r=new Random();
int n = r.nextInt(100);
if(n%2==0) throw new MyException();
else System.out.println(n);
}
}