Java学习笔记 - 第009天

每日要点

this的小用法

用this调用类其他的构造器

    public Fraction(int num, int den) {
        this.num = num;
        this.den = den;
        this.normalize();
        this.simplify();
    }

    public Fraction(double val) {
        this((int) (val * 10000), 10000);
    }
短除法

短除法 求两个数的最大公约数

    private int gcd(int x, int y) {
        if (x > y) {
            return gcd(y, x);
        }
        else if (y % x != 0) {
            return gcd(y % x, x);
        }
        else {
            return x;
        }
    }
枚举

枚举 : 定义符号常量的最佳方式
如果一个变量的值只有有限个选项通常都可以考虑使用枚举类型
看如下例题:
性别的枚举:

public enum Gender {
    MALE, FEMALE, UNKNOWN;
}

上下左右的枚举:

public enum Direction {
    UP, RIGHT, DOWN, LEFT;
}

昨天作业讲解

  • 1.写一个类 描述 数学上的分数 提供分数的加减乘除的运算 化简
    分数类:
/**
 * 分数 (有理数)
 * @author Kygo
 * @since 0.1
 */
public class Fraction {
    private int num;
    private int den;
    
    /**
     * 构造器 : 指定分子和分母创建分数对象
     * @param num 分子
     * @param den 分母
     */
    public Fraction(int num, int den) {
        this.num = num;
        this.den = den;
        this.normalize();
        this.simplify();
    }
    
    /**
     * 构造器
     * @param val 小数
     */
    // 用this调用类其他的构造器
    public Fraction(double val) {
        this((int) (val * 10000), 10000);
    }
    
    /**
     * 加法
     * @param other 另一个分数
     * @return 分数相加结果对象
     */
    public Fraction add(Fraction other) {
        return new Fraction(num * other.den + other.num * den, den * other.den);
    }
    
    /**
     * 减法
     * @param other 另一个分数
     * @return 分数相减结果对象
     */
    public Fraction sub(Fraction other) {
        return new Fraction(num * other.den - other.num * den, den * other.den);
    }
    
    /**
     * 乘法
     * @param other 另一个分数
     * @return 分数相乘结果对象
     */
    public Fraction mul(Fraction other) {
        return new Fraction(num * other.num, den * other.den);
    }
    
    /**
     * 除法
     * @param other 另一个分数
     * @return 分数相除结果对象
     */
    public Fraction div(Fraction other) {
        return new Fraction(num * other.den, den * other.num);
    }
    
    /**
     * 正规负号化方法 
     */
    public void normalize() {
        if (den < 0) {
            num = -num;
            den = -den;
        }
    }
    
    /**
     * 分数化简
     */
    public void simplify() {
        if (num != 0) {
            int x = num < 0 ? -num : num;
            int y = Math.abs(den);
            int factor = gcd(x, y);
            if (factor > 1) {
                num /= factor;
                den /= factor;
            }
        }
    }
    
    @Override
    public String toString() {
        if (num == 0) {
            return "0";
        }
        else if (den == 1) {
            return "" + num;
        }
        else {
            return num + "/" + den;
        }
    }
    
    // 短除法  求两个数的最大公约数
    private int gcd(int x, int y) {
        if (x > y) {
            return gcd(y, x);
        }
        else if (y % x != 0) {
            return gcd(y % x, x);
        }
        else {
            return x;
        }
    }
}

测试类:

        Fraction f1 = new Fraction(-2, -3);
        System.out.println(f1);
        Fraction f2 = new Fraction(0.75);
        System.out.println(f2);
        System.out.println(f1.add(f2));
        System.out.println(f1.sub(f2));
        System.out.println(f1.mul(f2));
        System.out.println(f1.div(f2));

例题

  • 1.设计一个扑克牌游戏类
    花色的设计:
    枚举
/**
 * 花色
 * @author Kygo
 *
 */
public enum Suite {
    SPADE, HEART, CLUB, DIAMOND, TRUMP;
}

一张牌类

/**
 * 一张牌
 * @author Kygo
 *
 */
public class Card {
    // 枚举
    private Suite suite;
    private int face;
    
    public Card(Suite suite, int face) {
        this.suite = suite;
        this.face = face;
    }
    
    @Override
    public String toString() {
        String str = "";
        switch (suite) {
        case SPADE: str = "♠"; break;
        case HEART: str = "❤"; break;
        case CLUB: str = "♣"; break;
        case DIAMOND: str = "♦"; break;
        case TRUMP: str = ""; break;
        }
        switch (face) {
        case 1: str += "A"; break;
        case 11: str += "J"; break;
        case 12: str += "Q"; break;
        case 13: str += "K"; break;
        case 15: str += "小王"; break;
        case 16: str += "大王"; break;
        default: str += face;
        }
        return str;
    }
}

一副牌类:

/**
 * 扑克
 * @author Kygo
 *
 */
public class Poker {
    private Card[] cardsArray = new Card[54];
    private int currentIndex;
    
    /**
     * 构造器 : 创建一副新牌
     */
    public Poker() {
        Suite[] suites = {Suite.SPADE, Suite.HEART, Suite.CLUB, Suite.DIAMOND};
/*      int[] faces = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        for (int i = 0; i < 52; i++) {
            cardsArray[i] = new Card(suites[i / 13], faces[i % 13]);
        }*/
        for (int i = 0; i < suites.length; i++) {
            for (int j = 0; j < 13; j++) {
                Card card = new Card(suites[i], j + 1);
                cardsArray[i*13 + j] = card;
            }
        }
        cardsArray[52] = new Card(Suite.TRUMP, 15);
        cardsArray[53] = new Card(Suite.TRUMP, 16);
    }
    
    /**
     * 洗牌 : 随机乱序
     */
    public void shuffle() {
        for (int i = 0, len = cardsArray.length; i < len; i++) {
            int randomIndex = (int) (Math.random() * len);
            Card temp = cardsArray[i];
            cardsArray[i] = cardsArray[randomIndex];
            cardsArray[randomIndex] = temp;
        }
        currentIndex = 0;
    }
    
    /**
     * 发牌
     * @return 一张牌
     */
    public Card deal() {
        return cardsArray[currentIndex++];
    }
    
    /**
     * 判断还有没有牌可以发出
     * @return 还有牌返回true 否则返回false
     */
    public boolean hasMoreCards() {
        return currentIndex < cardsArray.length;
    }
}

测试类:

    public static void display(Player player) {
        System.out.print(player.getName() + ":");
        for (Card card : player.showCards()) {
            System.out.print(card);
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        Player[] playersArray = {
                new Player("张三"),
                new Player("李四"),
                new Player("王五"),
                new Player("小白")
        };
        Poker poker = new Poker();
        poker.shuffle();
        for (int round = 1; round <= 3; round++) {
            for (Player player : playersArray) {
                player.getOneCard(poker.deal());
            }
        }
        
        // 显示每个玩家手上的牌
        for (Player player : playersArray) {
            display(player);
        }
    }
  • 2.猜数字机器人游戏设计
    猜数字机器人类:
/**
 * 猜数字机器人
 * @author Kygo
 *
 */
public class Robot {
    private int answer;
    private String hint;
    private int counter;
    
    /**
     * 构造器
     */
    public Robot() {
        this.reset();
    }
    
    /**
     * 判断有没有猜中数字
     * @param thyAnswer 玩家猜的数字
     * @return 如果玩家猜中了数字返回true否则返回false
     */
    public boolean judge(int thyAnswer) {
        counter += 1;
        if (thyAnswer == answer) {
            hint = "恭喜你,猜对了!";
            return true;
        }
        else if (thyAnswer > answer) {
            hint = "小一点";
        }
        else {
            hint = "大一点";
        }
        return false;
    }
    
    /**
     * 重置(重新出随机数,计算器清零,提示信息清空)
     */
    public void reset() {
        answer = (int) (Math.random() * 100 + 1);
        counter = 0;
        hint = "";
    }
    
    /**
     * 获取给用户的提示
     * @return 提示字符串
     */
    public String getHint() {
        return hint;
    }
    
    /**
     * 获取用户猜的次数
     * @return 次数
     */
    public int getCounter() {
        return counter;
    }
}

玩家类:

/**
 * 玩家
 * @author Kygo
 *
 */
public class Player {
    private String name;
    private Card[] cardsOnHand;
    private int totalCards;
    
    /**
     * 构造器
     * @param name 玩家姓名
     */
    public Player(String name) {
        this.name = name;
        cardsOnHand = new Card[3];
    }
    
    /**
     * 摸一张牌
     * @param card 一张牌
     */
    public void getOneCard(Card card) {
        if (totalCards < cardsOnHand.length) {
            cardsOnHand[totalCards++] = card;
        }
    }
    
    /**
     * 亮牌
     * @return 玩家手上所有牌的数组
     */
    public Card[] showCards() {
        return cardsOnHand;
    }
    
    /**
     * 获得玩家的姓名
     * @return 玩家姓名
     */
    public String getName() {
        return name;
    }
}

测试类:

        Robot robot = new Robot();
        Scanner input = new Scanner(System.in);
        boolean isCorrect = false;
        do {
            System.out.print("请输入你猜的数字: ");
            int thyAnswer = input.nextInt();
            isCorrect = robot.judge(thyAnswer);
            System.out.println(robot.getHint());
        } while (!isCorrect);
        if (robot.getCounter() > 7) {
            System.out.println("你的智商余额明显不足!");
        }
        input.close();

作业

  • **1.Craps赌博游戏 - 面向对象 **
    **两颗色子 - **
    第一次:
    玩家摇出 7 和11 玩家胜 2 3 或12 庄家胜 其他点数 游戏继续
    玩家再摇
    如果摇出7点 庄家胜 如果摇出了第一次的点数 玩家胜 其他情况 游戏继续

骰子类:

public class Dice {
    private int face;
    
    public Dice() {
        this.rollDice();
    }
    
    public int rollDice() {
        return face = (int) (Math.random() * 6 + 1);
    }
    
    public String display() {
        return "摇出了" + face + "点.";
    }
}

玩家类:

public class Dice {
    private int face;
    
    public Dice() {
        this.rollDice();
    }
    
    public int rollDice() {
        return face = (int) (Math.random() * 6 + 1);
    }
    
    public String display() {
        return "摇出了" + face + "点.";
    }
}

游戏类:

public class CrapsGame {
    private String hint;
    private boolean needsGoOn;
    private int fistPoint;
    private int currentPoint;
    private Player p;
    private int bet;

    public CrapsGame(Player p) {
        this.p = p;
        hint = "";
    }
    
    public void game(int bet) {
        this.bet = bet;
        if (bet >= 0 && bet <= p.getMoney()) {
            fistPoint = p.rollDices();
            System.out.println(p.display());
            switch (fistPoint) {
            case 7:
            case 11:
                p.setMoney(p.getMoney() + bet);
                hint = "玩家: " + p.getName() + "获胜!";
                needsGoOn = false;
                break;
            case 2:
            case 3:
            case 12:
                p.setMoney(p.getMoney() - bet);
                hint = "庄家获胜!";
                needsGoOn = false;
                break;
            default:
                needsGoOn = true;
                gameGoOn();
                break;
            }
        }
        else {
            hint = "你没有那么多钱";
        }
    }
    
    public void gameGoOn() {
        while (needsGoOn) {
            currentPoint = p.rollDices();
            System.out.println(p.display());
            if (currentPoint == 7) {
                p.setMoney(p.getMoney() - bet);
                hint = "庄家获胜!";
                needsGoOn = false;
            } else if (currentPoint == fistPoint) {
                p.setMoney(p.getMoney() + bet);
                hint = "玩家: " + p.getName() + "获胜!";
                needsGoOn = false;
            } 
        }
    }
    
    public String getHint() {
        return hint;
    }

    public boolean isNeedsGoOn() {
        return needsGoOn;
    }
    
}

测试类:

/*      Dice dice = new Dice();
        System.out.println(dice.display());*/
        Player p = new Player("张三", 1000);
        CrapsGame crapsGame = new CrapsGame(p);
        Scanner input = new Scanner(System.in);
        do {
            System.out.println(p.showMoney());
            System.out.print("请下注:");
            int bet = input.nextInt();
            crapsGame.game(bet);
            System.out.println(crapsGame.getHint());
        } while (p.getMoney() > 0);
        System.out.println(p.showMoney());
        System.out.println("游戏结束.");
        input.close();
  • 2.自动售货机 - 面向对象
    商品类:
public class Goods {
    private String name;
    private int price;
    private int count;
    
    public Goods(String name, int price, int count) {
        this.name = name;
        this.price = price;
        this.count = count;
    }

    public String showGoods() {
        return "商品名称: " + name + "  商品价格: " + price + "元"
                +" 商品数量: " + count;
    }
    
    public int getPrice() {
        return price;
    }
    
    public String getName() {
        return name;
    }
    
    public int getCount() {
        return count;
    }
    
    public void setCount(int count) {
        this.count = count;
    }
}

人类:

public class Person {
    private String name;
    private int money;
    private String buyGoods;
    
    public Person(String name, int money) {
        this.name = name;
        this.money = money;
    }

    public void shopping(Goods goods) {
        if (money > goods.getPrice()) {
            money -= goods.getPrice();
            goods.setCount(goods.getCount() - 1);
            System.out.printf("%s花费%d元购买了%s,还剩%d元\n", name, goods.getPrice(),
                    goods.getName(), money);
        }
        else {
            System.out.println("钱不够.");
        }
    }
    
    public int getMoney() {
        return money;
    }
    
    public void setMoney(int money) {
        this.money = money;
    }
    
    public String getName() {
        return name;
    }
    
    public String getBuyGoods() {
        return buyGoods;
    }
    
    public void setBuyGoods(String buyGoods) {
        this.buyGoods = buyGoods;
    }
}

售货机类:

public class VendingMachine {
    private Goods[] goods;
    private String goodsInfo;
    private int goodsIndex;
    
    public VendingMachine(Goods[] goods) {
        this.goods = goods;
        this.goodsInfo = "";
    }
    
    public void sell(Person p) {
        for (int i = 0; i < goods.length; i++) {
            if (p.getBuyGoods().equals(goods[i].getName())) {
                goodsIndex = i;
            }
        }
        p.shopping(goods[goodsIndex]);
    }
    
    public String show() {
        String gi = "";
        for (Goods g : goods) {
            gi += g.showGoods() + "\n";
        }
        goodsInfo = gi;
        return goodsInfo;
    }
}

测试类:

        Goods goods1 = new Goods("可乐", 3, 10);
        Goods goods2 = new Goods("雪碧", 3, 10);
        Goods goods3 = new Goods("啤酒", 3, 10);
        Person person = new Person("张三", 100);
        VendingMachine vm = new VendingMachine(new Goods[]{goods1, goods2, goods3});
        System.out.println("本自动售货机出售以下物品: ");
        System.out.println(vm.show());  
        Scanner input = new Scanner(System.in);
        System.out.println("请输入你想买的商品: ");
        String wantBuy = input.nextLine();
        person.setBuyGoods(wantBuy);
        vm.sell(person);
        System.out.println(vm.show());
        input.close();

你可能感兴趣的:(Java学习笔记 - 第009天)