本帖最後由 吳尚哲 於 2012-10-14 21:12 編輯
- public class BMIManager
- {
- String mName;
- float mHeight;
- float mWeight;
- boolean mSex;
- float mBMI;
- String mSuggestion;
-
- BMIManager(String n, float h, float w, boolean s) //建構子
- {
- this.mName = n;
- this.mHeight = h;
- this.mWeight = w;
- this.mSex = s;
- }
-
- void setName(String n)
- {
- this.mName = n;
- }
-
- void setHeight(float h)
- {
- this.mHeight = h;
- }
-
- void setWeight(float w)
- {
- this.mHeight = w;
- }
-
- void setSex(boolean s)
- {
- this.mSex = s;
- }
-
- float getHeight()
- {
- return this.mHeight;
- }
-
- float getWeight()
- {
- return this.mWeight;
- }
-
- boolean getSex()
- {
- return this.mSex;
- }
-
- float caculateBMI()
- {
- this.mBMI = this.mWeight/((this.mHeight/100)*(this.mHeight/100));
- return this.mBMI;
- }
-
- String suggestion()
- {
- if(this.mBMI >= 35)
- {
- this.mSuggestion = this.mName + "重度肥胖";
- }
-
- else if(this.mBMI >= 30 && this.mBMI < 35)
- {
- this.mSuggestion = this.mName + (mSex?"先生":"女士") +"中度肥胖 BMI:" + this.mBMI;
- }
-
- else if(this.mBMI >= 27 && this.mBMI < 30)
- {
- this.mSuggestion = this.mName + (mSex?"先生":"女士") + "輕度肥胖 BMI:" + this.mBMI;
- }
-
- else if(this.mBMI >= 24 && this.mBMI < 27)
- {
- this.mSuggestion = this.mName + (mSex?"先生":"女士") + "過重 BMI:" + this.mBMI;
- }
-
- else if(this.mBMI >= 18.5 && this.mBMI < 24)
- {
- this.mSuggestion = this.mName + (mSex?"先生":"女士") + "標準 BMI:" + this.mBMI;
- }
-
- else if(this.mBMI < 18.5)
- {
- this.mSuggestion = this.mName + (mSex?"先生":"女士") + "過輕 BMI:" + this.mBMI;
- }
-
- else
- {
- this.mSuggestion = "你確定??" + this.mBMI;
- }
-
- return this.mSuggestion;
- }
- }
複製代碼- import java.util.Scanner;
- public class MyBMI {
- public static void main(String[] args)
- {
- Scanner scan = new Scanner(System.in);
- String name;
- float h;
- float w;
- boolean s;
- System.out.println("請輸入您的大名 : ");
- name = scan.next();
- System.out.println("請輸入您的身高(公分) : ");
- h = Float.parseFloat(scan.next());
- System.out.println("請輸入您的體重(公斤) : ");
- w = Float.parseFloat(scan.next());
- System.out.println("請輸入您的性別男1/女0 : ");
- s = Integer.parseInt(scan.next())==1;
-
- BMIManager myBMI = new BMIManager(name, h, w, s);
-
- myBMI.caculateBMI();
- System.out.println(myBMI.suggestion());
- }
- }
複製代碼- 請輸入您的大名 :
- 阿哲
- 請輸入您的身高(公分) :
- 170
- 請輸入您的體重(公斤) :
- 78
- 請輸入您的性別男1/女0 :
- 1
- 阿哲先生過重 BMI:26.989618
複製代碼 老師我想請教一下
建構子的功能是在物件實體化的過程中將內容初始化而已嗎?
除此之外還有其他用意嗎?
和用set方法給予初始值有什麼不一樣? |