Repository navigation
Expand file tree
/
Copy pathBai2.java
More file actions
87 lines (70 loc) · 2.45 KB
/
Copy pathBai2.java
File metadata and controls
87 lines (70 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package Chuong3;
import java.util.Scanner;
// Bài 2: Lớp HINHCHUNHAT
class HinhChuNhat {
private float dai;
private float rong;
// Hình mặc định 1 x 1 để luôn có kích thước hợp lệ
public HinhChuNhat() {
dai = 1;
rong = 1;
}
// Kích thước không hợp lệ (<= 0) thì giữ giá trị mặc định 1
public HinhChuNhat(float dai, float rong) {
this();
setDai(dai);
setRong(rong);
}
private static boolean hopLe(float d) {
return d > 0 && Float.isFinite(d);
}
public float getDai() { return dai; }
public float getRong() { return rong; }
// Trả về false và giữ giá trị cũ nếu kích thước không hợp lệ
public boolean setDai(float dai) {
if (!hopLe(dai)) return false;
this.dai = dai;
return true;
}
public boolean setRong(float rong) {
if (!hopLe(rong)) return false;
this.rong = rong;
return true;
}
// Kiểm tra SAU khi ép sang float bằng chính setter: 1e100 thành vô cực,
// 1e-100 thành 0 đều bị setter từ chối nên phải nhập lại
public void nhap(Scanner sc) {
while (!setDai((float) NhapLieu.soDuong(sc, "Nhap chieu dai: "))) {
System.out.println("Gia tri vuot pham vi float duong, nhap lai!");
}
while (!setRong((float) NhapLieu.soDuong(sc, "Nhap chieu rong: "))) {
System.out.println("Gia tri vuot pham vi float duong, nhap lai!");
}
}
// Tính bằng double: tích hai số float lớn (vd 1e30 x 1e30) vượt phạm vi float
public double tinhDienTich() {
return (double) dai * rong;
}
public double tinhChuVi() {
return ((double) dai + rong) * 2;
}
public void xuat() {
System.out.println("Hinh chu nhat: dai = " + dai + ", rong = " + rong);
System.out.println(" Dien tich = " + tinhDienTich());
System.out.println(" Chu vi = " + tinhChuVi());
}
}
public class Bai2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HinhChuNhat hcn1 = new HinhChuNhat();
hcn1.nhap(sc);
hcn1.xuat();
HinhChuNhat hcn2 = new HinhChuNhat(5, 3);
hcn2.xuat();
// Kích thước âm bị từ chối, hình giữ kích thước hợp lệ
HinhChuNhat hcn3 = new HinhChuNhat(-5, 3);
hcn3.xuat();
sc.close();
}
}