写给xx看之用面向对象编程解决行测数量关系题哈哈哈

204 阅读2分钟

test.jpg

拿到题后寻思手算也太麻烦了, 于是乎。。。

懒是第一生产力! 写程序盘他 !

面向对象编程名词:

  • class: 一类事物, 例如人, 车, 水果
  • 实例 instance: 类的具体化, 香蕉, 葡萄, 实例与类是 is-a 的关系, 例如香蕉是一种 (is-a) 水果, xx 是人
  • 属性 property: 例如人的身高体重
  • 方法 method: 跑, 跳, 吃 可以作为一个人的 method

于是乎, 可以设计一个代表酒的类 Alocoho, 拥有以下属性:

  • weight: 酒质量
  • percentage: 酒精浓度
  • water: 水的质量
  • alcoho: 酒精的质量 以及以下方法:
  • drink 被喝掉多少酒的方法
  • addWater 加水的方法
  • mix 混合两瓶酒的方法

因此这道题目可以被翻译成这样的过程:

// 初始总质量
float totalWeight = 100;
        
// 初始化两瓶酒质量为 100, 酒精浓度为 60% 的酒 a 和 b
Alcoho a = new Alcoho(totalWeight, 0.6f);
Alcoho b = new Alcoho(totalWeight, 0.6f);

// a 喝掉一半
a.drink(1.0f/2);
// b 喝掉 1/6
b.drink(1.0f/6);
// a 加满
a.addWater(totalWeight - a.weight);
// b 加满
b.addWater(totalWeight - b.weight);

// a 再喝 1/3
a.drink(1.0f/3);
// b 再喝一半
b.drink(1.0f/2);
// a 再加满
a.addWater(totalWeight - a.weight);

// 混合 a b 两瓶酒得到酒 c
Alcoho c = a.mix(b);
// 打印 c 的酒精含量

完整的代码如下啦:

// 酒
class Alcoho {
    // 酒的质量
    float weight;
    // 酒精浓度
    float percentage;
    
    // 酒里酒精的质量
    float alcoho;
    // 酒里水的质量
    float water;
    
    // 根据当前酒的质量和酒精浓度
    // 计算里面含有的酒精和水的质量
    void calculate () {
        this.alcoho = this.weight * this.percentage;
        this.water = this.weight - this.alcoho;
    }
    
    Alcoho(float weight, float percentage) {
        // 初始化一瓶酒, 指定其初始质量 weight 以及含酒精浓度 percentage
        this.weight = weight;
        this.percentage = percentage;
        
        calculate();
    }
    
    // 喝掉百分之多少的酒
    void drink(float percentage) {
        this.weight = this.weight - percentage * this.weight;
        calculate();
    }
    
    // 加水
    void addWater(float addedWater) {
        this.weight = this.weight + addedWater;
        this.percentage = this.alcoho / this.weight;
        calculate();
    }
    
    // 混合另一瓶酒 a, 返回 (return) 一瓶新的酒
    Alcoho mix(Alcoho a) {
        float weight = this.weight + a.weight;
        float percentage = (this.alcoho + a.alcoho) / weight;
        return new Alcoho(weight, percentage);
    }
}

public class Main {
    public static void main(String[] args) {
        float totalWeight = 100;
        
        // 初始化两瓶酒质量为 100, 酒精浓度为 60% 的酒 a 和 b
        Alcoho a = new Alcoho(totalWeight, 0.6f);
        Alcoho b = new Alcoho(totalWeight, 0.6f);
        
        // a 喝掉一半
        a.drink(1.0f/2);
        // b 喝掉 1/6
        b.drink(1.0f/6);
        // a 加满
        a.addWater(totalWeight - a.weight);
        // b 加满
        b.addWater(totalWeight - b.weight);
        
        // a 再喝 1/3
        a.drink(1.0f/3);
        // b 再喝一半
        b.drink(1.0f/2);
        // a 再加满
        a.addWater(totalWeight - a.weight);
        
        // 混合 a b 两瓶酒得到酒 c
        Alcoho c = a.mix(b);
        // 打印 c 的酒精含量
        System.out.println(c.percentage);
    }
}

最终得到运行结果 0.3 嘿嘿