P2-9 案例:标准体重计算器

案例:标准体重计算器


需求说明

GUI需求说明1

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
String 性别 = GUI.buttonsBox("请选择你的性别","男性","女性");
double 身高 = GUI.doubleBox("请输入你的身高(cm)");
double 体重 = GUI.doubleBox("请输入你的体重(kg)");
if (性别.equals("男性"))
{
//男性:标准体重=(身高cm-80)*70%
double 标准体重 = (身高-80)*0.70;
//String newtizhong = String.format("%.2f",tizhong);//doubel保留两位小数
//double result = Double.parseDouble(newtizhong);
double 和标准体重的差 =((体重-标准体重)/标准体重)*100;
if (和标准体重的差<=10||和标准体重的差>=-10)
{
System.out.println("体重为正常");
}
else if (和标准体重的差>10&&和标准体重的差<=20)
{
System.out.println("体重为偏胖");
}
else if (和标准体重的差<-10&&和标准体重的差>-20)
{
System.out.println("体重为偏瘦");
}
else if (和标准体重的差>20)
{
System.out.println("体重为肥胖");
}
else if (和标准体重的差<-20)
{
System.out.println("体重为瘦弱");
}


}
else if (性别.equals("女性"))
{
//女性:标准体重=(身高cm-70)*60%

double 标准体重 = (身高-70)*0.60;
double 和标准体重的差 =((体重-标准体重)/标准体重)*100;
if (和标准体重的差<=10||和标准体重的差>=-10)
{
System.out.println("体重为正常");
}
else if (和标准体重的差>10&&和标准体重的差<=20)
{
System.out.println("体重为偏胖");
}
else if (和标准体重的差<-10&&和标准体重的差>-20)
{
System.out.println("体重为偏瘦");
}
else if (和标准体重的差>20)
{
System.out.println("体重为肥胖");
}
else if (和标准体重的差<-20)
{
System.out.println("体重为瘦弱");
}

}

分析代码

  • 发现自己写的代码有复制粘贴的行为,违反了DRY原则(不要重复自己)
  • 进行优化
    • 1.命名优化
    • 2.把违反DRY原则的代码重复利用起来
    • 3.改成弹窗显示结果
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
String gender = GUI.buttonsBox("请选择你的性别","男性","女性");
double height = GUI.doubleBox("请输入你的身高(cm)");
double weight = GUI.doubleBox("请输入你的体重(kg)");
double standardWeight;
if (gender.equals("男性"))
{
//男性:标准体重=(身高cm-80)*70%
standardWeight = (height-80)*0.70;
}
else
{
//女性:标准体重=(身高cm-70)*60%
standardWeight = (height-70)*0.60;
}
double weightDeviation =((weight-standardWeight)/standardWeight)*100;
if (weightDeviation<=10||weightDeviation>=-10)//10%或-10%
{
GUI.msgBox("你很正常哦~");
}
else if (weightDeviation>10&&weightDeviation<=20)//10%-20%
{
GUI.msgBox("你稍微有点一点点胖哦");;
}
else if (weightDeviation<-10&&weightDeviation>-20)//-10%--->-20%
{
GUI.msgBox("你稍微有点一点点瘦哦");
}
else if (weightDeviation>20)//20%--->
{
GUI.msgBox("你太胖了,该减肥了");
}
else if (weightDeviation<-20)//-20%--->
{
GUI.msgBox("你太廋了,多吃点");
}

P2-9 案例:标准体重计算器
http://example.com/2024/08/06/SE101-零基础玩Java/Part2-笔记/P2-9 案例:标准体重计算器/
Author
John Doe
Posted on
August 6, 2024
Licensed under