返回本章節
返回作業目錄
需求說明:
編寫 Java 程序,定義 Java 類 Point 用來表示座標,座標範圍在(0,0)到(100,100)以內,並顯示合法的座標在控制檯。
實現思路:
定義 Point 類,爲該類分別定義兩個屬性 X 和 Y,用來表示橫座標和縱座標。
爲 Point 類定義兩個構造方法,分別是無參構造方法和有參構造方法。
在有參構造方法中完成對參數的判定,如果不滿足座標範圍則給出錯誤提示且給座標一個(1,1)初始座標,如果參數符合標準,則完成對屬性 X 和 Y 的賦值。
定義 Point 類的 show 方法,完成 X 和 Y 的打印。
實現代碼:
public class Point {
int x;
int y;
public Point(int i, int j) {
// TODO Auto-generated constructor stub
}
public void Point(int a,int b) {
if((x<100&&x>0)&&(y<100&&y>0)) {
x = a;
y = b;
}else {
System.out.println("橫座標或縱座標的取值不符合規範");
x = 1;
y = 1;
}
}
public void show() {
System.out.printf("當前的座標爲%d:%d",x,y);
}
public static void main(String[] args) {
Point p1 = new Point(88,77);
p1.show();
Point p2 = new Point(150,200);
p2.show();
}
}