Java學習筆記 - 第008天

每日要點

修改器和訪問器

修改器 - 屬性的setter方法

    public void setXxx(T t) {
        this.t = t;
    }

訪問器 - 屬性的getter方法

    public T getXxx() {
        return t;
    }
toString()

將對象轉換成字符串輸出

@Override
public String toString() {
    // TODO Auto-generated method stub
    return super.toString();
}

文檔注釋
用來描述自己定義的類、變量、方法等,例如:

/**
 * 平面上的點
 * @author Kygo
 * @since 0.1
 */

昨天作業修正

  • 1.定義一個類 描述手機 品牌尺寸等 打電話 發短信等call send short message install application Appuninstall / remove update
    手機類:
  public class MobilePhone {
    private String brand;
    private String owner;
    private double size;
    private double price;
    private boolean isSmart;
    private String[] installedApps;
    private int numberOfApps;
    
    public MobilePhone(String brand, double size, double price, boolean isSmart) {
        this.brand = brand;
        this.size = size;
        this.price = price;
        this.isSmart = isSmart;
        if (this.isSmart) {
            this.installedApps = new String[100];
        }
    }

    // 修改器 - 屬性的setter方法
    public void setOwner(String owner) {
        this.owner = owner;
    }
    
    // 訪問器 - 屬性的getter方法
    public String getOwner() {
        return owner;
    }
    
    public void show() {
        System.out.println(owner + "的價值" + price + "元的" + size +
                "英寸的" + brand + "手機");
    }
    
    public void call(String tel) {
        System.out.println("正在呼叫" + tel + "...");
    }
    
    public void sendShortMessage(String[] tels, String content) {
        for (String tel : tels) {
            System.out.println("向" + tel + "發送信息: " + content);
        }
    }
    
    public void installApp(String appName) {
        if (isSmart && numberOfApps < installedApps.length) {
            System.out.println("正在安裝" + appName);
            installedApps[numberOfApps] = appName;
            numberOfApps += 1;
        }
        else {
            System.out.println("不能安裝應用程序.");
        }
    }
    
    public void uninstallApp(String appName) {
        if (isSmart) {
            for (int i = 0; i < numberOfApps; i++) {
                if (installedApps[i].equals(appName)) {
                    System.out.println("正在卸載" + appName);
                    for (int j = i; j < numberOfApps - 1; j++) {
                        installedApps[j] = installedApps[j + 1];
                    }
                    numberOfApps -= 1;
                    return;
                }
            }
            System.out.println("沒有這個應用程序.");
        }
        else {
            System.out.println("不能卸載應用程序.");
        }
    }
    
    public void runApp(String appName) {
        for (int i = 0; i < numberOfApps; i++) {
            if (installedApps[i].equals(appName)) {
                System.out.println("啟動" + appName);
                return ;
            }
        }
        System.out.println("沒有對應應用程序");
    }
}

測試類:

        MobilePhone phone1 = new MobilePhone("iphone 5S", 4, 2000, true);
        phone1.setOwner("張三");
        System.out.println(phone1.getOwner());
        phone1.show();
        phone1.installApp("捕魚達人");
        phone1.installApp("微信");
        phone1.runApp("微信");
        phone1.runApp("歡樂斗地主");
        phone1.call("110");
        phone1.sendShortMessage(new String[] {"13213213", "1231242"},"晚上約嗎");
        
        MobilePhone phone2 = new MobilePhone("山寨", 3, 200, false);
        phone2.setOwner("王大錘");
        phone2.show();
        phone2.installApp("王室戰爭");
  • 2.寫個程序 模擬 奧特曼打小怪獸hp mp攻擊行為攻擊參數 小怪獸奧特曼必殺技小怪獸反擊
    奧特曼類:
public class Ultraman {
    private String name;
    private int hp;
    private int mp;
    
    public Ultraman(String name, int hp, int mp) {
        this.name = name;
        this.setHp(hp);
        this.mp = mp;
    }
    
    public String info() {
        return String.format("%s奧特曼 - 生命值: %d, 魔法值: %d",
                name, getHp(), mp);
    }

    public void attack(Monster m) {
        int injury = (int) (Math.random() * 11 + 10);
        m.setHp(m.getHp() - injury);
    }
    
    public void hugeAttack(Monster m) {
        if (mp >= 40) {
            int injury = m.getHp() / 4 * 3 > 50 ? m.getHp() / 4 * 3 : 50;
            m.setHp(m.getHp() - injury);
            mp -= 40;
        }
    }
    
    public void magicalAttack(Monster[] mArray) {
        if (mp >= 15) {
            for (Monster m : mArray) {
                if (m.getHp() > 0) {
                    int injury = (int) (Math.random() * 11 + 5);
                    m.setHp(m.getHp() - injury);
                }
            }
            mp -= 15;
        }
    }

    public void resumeMp() {
        mp += 4;
    }
    
    public int getHp() {
        return hp;
    }

    public void setHp(int hp) {
        this.hp = hp > 0 ? hp : 0;
    }

    public int getMp() {
        return mp;
    }
}

小怪獸類:

public class Monster {
    private String name;
    private int hp;
    
    public Monster(String name, int hp) {
        this.name = name;
        this.setHp(hp);
    }

    public String info() {
        return String.format("%s小怪獸 - 生命值: %d", name, getHp());
    }
    
    public void attack(Ultraman u) {
        int injury = (int) (Math.random() * 6 + 5);
        u.setHp(u.getHp() - injury);
    }

    public int getHp() {
        return hp;
    }

    public void setHp(int hp) {
        this.hp = hp < 0 ? 0 : hp;
    }
}

測試類:

    public static Monster selectOne(Monster[] mArray) {
        Monster temp = null;
        do {
            int randomIndex = (int) (Math.random() * mArray.length);
            temp = mArray[randomIndex];
        } while (temp.getHp() == 0);
        return temp;
    }
    
    public static void showMonsterInfo(Monster[] mArray) {
        for (Monster monster : mArray) {
            System.out.println(monster.info()); 
        }
    }
    
    public static boolean isAllDead(Monster[] mArray) {
        for (Monster monster : mArray) {
            if (monster.getHp() > 0) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        Ultraman u = new Ultraman("迪迦", 250, 150);
        System.out.println(u.info());
        Monster m1 = new Monster("哥斯拉", 100);
        Monster m2 = new Monster("暴龍", 120);
        Monster m3 = new Monster("金剛", 140);
        Monster m4 = new Monster("異形", 150);
        Monster[] mArray = {m1, m2, m3, m4};
        showMonsterInfo(mArray);
        int round = 1;
        do {
            System.out.println("======第" + round + "回合======");
            int random = (int) (Math.random() * 10 + 1);
            Monster m = selectOne(mArray);
            if (random <= 7) {
                useNormalAttack(u, m);
            }
            else if (random <= 9) {
                if (u.getMp() >= 15) {
                    System.out.println("奧特曼使用了魔法攻擊.");
                    u.magicalAttack(mArray);
                    for (Monster monster : mArray) {
                        if (monster.getHp() > 0) {
                            monster.attack(u);
                        }
                    } 
                }
                else {
                    useNormalAttack(u, m);
                }
            }
            else {
                if (u.getMp() >= 40) {
                    System.out.println("奧特曼使用了究極必殺技.");
                    u.hugeAttack(m);
                    if (m.getHp() > 0) {
                        m.attack(u);
                    } 
                }
                else {
                    useNormalAttack(u, m);
                }
            }
            if (u.getHp() > 0) {
                u.resumeMp();
            }
            System.out.println(u.info());
            showMonsterInfo(mArray);
            round += 1;
        } while (u.getHp() > 0 && !isAllDead(mArray));
        if (u.getHp() > 0) {
            System.out.println("奧特曼勝利!");
        }
        else {
            System.out.println("小怪獸勝利!");
        }
    }

    public static void useNormalAttack(Ultraman u, Monster m) {
        System.out.println("奧特曼使用了普通攻擊.");
        u.attack(m);
        if (m.getHp() > 0) {
            m.attack(u);
        }
    }
  • **3.改造成面向對象 圍墻 過道 **
    圓類:
public class Circle {

    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }

    public double perimeter() {
        return 2 * Math.PI * radius;
    }
    
    public double area() {
        return Math.PI * radius * radius;
    }
}

測試類:

    private static final double AISLE_UNIT_PRICE = 38.5;
    private static final double FENCE_UNIT_PRICE = 15.5;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("請輸入游泳池的半徑: ");
        double r = input.nextDouble();
        Circle small = new Circle(r);
        Circle big = new Circle(r + 3);
        System.out.printf("圍墻的造價為: ¥%.2f元\n",
                big.perimeter() * FENCE_UNIT_PRICE);
        System.out.printf("過道的造價為: ¥%.2f元\n",
                (big.area() - small.area()) * AISLE_UNIT_PRICE);
        input.close();
    }

練習

  • 1.定義一個類描述矩形
public class Rectangle {
    private double height;
    private double width;
    
    public Rectangle(double height, double width) {
        this.height = height;
        this.width = width;
    }

    public double perimeter() {
        return 2 * (height + width);
    }
    
    public double area() {
        return height * width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }
}

例題

  • 1.定義一個類描述平面 點 可以移動修改點 能計算這個點到另外一個點的距離
    點類:
/**
 * 平面上的點
 * @author Kygo
 * @since 0.1
 */
// 定義一個類描述平面  點 可以移動修改點 能計算這個點到另外一個點的距離
public class Point {
    private double x;  // 橫坐標
    private double y;  // 縱坐標
    
    /**
     * 構造器
     * @param x 橫坐標
     * @param y 縱坐標
     */
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
        // this.moveTo(x, y);
    }
    
    /**
     * 移動到
     * @param newX 新的橫坐標
     * @param newY 新的縱坐標
     */
    // 移動到
    public void moveTo(double newX, double newY) {
        x = newX;
        y = newY;
    }
    
    /**
     * 移動了
     * @param dx 橫坐標的增量
     * @param dy 縱坐標的增量
     */
    // 移動了
    public void moveBy(double dx, double dy) {
        x += dx;
        y += dy;
    }
    
    /**
     * 計算到另一個點的距離
     * @param other 另一個點
     * @return 兩個點的距離
     */
    public double distanceTo(Point other) {
        // this到other的距離
        double dx = this.x - other.x;
        double dy = this.y - other.y;
        return Math.sqrt(dx * dx + dy * dy);
    }
    
    // 將對象轉換成字符串輸出
    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }
}
  • 2.定義一條線段
// 文檔注釋
/**
 * 平面上的線條
 * @author Kygo
 * @since 0.2
 */
//定義一條線段
public class Line {
    private Point start;
    private Point end;
    
    /**
     * 構造器
     * @param start 線段的起點
     * @param end 線段的終點
     */
    public Line(Point start, Point end) {
        this.start = start;
        this.end = end;
    }

    /**
     * 獲取線段的長度
     * @return 線段的長度
     */
    public double length() {
        return start.distanceTo(end);
    }   
}

作業

  • 1.寫一個類 描述 數學上的分數 提供分數的加減乘除的運算 化簡
    分數類:
public class Fraction {
    private int numerator;  // 分子
    private int denominator;  // 分母
    
    public Fraction(int numerator, int denominator) {
        this.numerator = numerator;
        this.denominator = denominator;
    }

    public Fraction add(Fraction f) {
        Fraction result = new Fraction(0, 0);
        result.numerator = (this.numerator * f.denominator) + 
                (f.numerator * this.denominator);
        result.denominator = this.denominator * f.denominator;
        result.reduction();
        return result; 
    }
    
    public Fraction subtract(Fraction f) {
        Fraction result = new Fraction(0, 0);
        result.numerator = (this.numerator * f.denominator) - 
                (f.numerator * this.denominator);
        result.denominator = this.denominator * f.denominator;
        result.reduction();
        return result;
    }
    
    public Fraction multiply(Fraction f) {
        Fraction result = new Fraction(0, 0);
        result.denominator = this.denominator * f.denominator;
        result.numerator = this.numerator * f.numerator;
        result.reduction();
        return result;
    }
    
    public Fraction divide(Fraction f) {
        Fraction result = new Fraction(0, 0);
        result.denominator = this.denominator * f.numerator;
        result.numerator = this.numerator * f.denominator;
        result.reduction();
        return result;
    }
    
    public void reduction() {
        int min = denominator > Math.abs(numerator) ? Math.abs(numerator) : denominator;
        for (int i = min; i >= 2; i--) {
            if (numerator % i == 0 && denominator % i == 0) {
                numerator /= i;
                denominator /= i;
                return ;
            }
        }
    }
    
    @Override
    public String toString() {
        if (numerator != 0) {
            return numerator + "/" + denominator;
        }
        else {
            return "0";
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 每日要點 面向對象的四大支柱 抽象 - 定義一個類的過程就是一個抽象的過程(數據抽象、行為抽象),通過抽象我們可以...
    迷茫o閱讀 399評論 0 0
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • 2017.04.09 孫愈顏奇跡感恩日志 一、奇跡 ...
    幸福花開奇跡匯閱讀 160評論 0 1
  • 就算你我世界至此互不相干 我也要讓你看到我的優秀
    SwanOdette閱讀 184評論 0 0