美文网首页
Java学习笔记 - 第007天

Java学习笔记 - 第007天

作者: 迷茫o | 来源:发表于2016-12-06 20:40 被阅读0次

    每日要点

    二维数组

    int a[][] = new int[2][3];
    二维数组 a 可以看成一个两行三列的数组。

    • 例子1:学生的成绩
            int[][] scores = new int[5][3];
            for (int i = 0; i < scores.length; i++) {
                for (int j = 0; j < scores[i].length; j++) {
                    scores[i][j] = (int) (Math.random() * 101);
                }
            }
    
    • 例子2:杨辉三角:
      1
      1 1
      1 2 1
      1 3 3 1
      1 4 6 4 1
      1 5 10 10 5 1
             int[][] y = new int[10][];
             for (int i = 0; i < y.length; i++) {
                y[i] = new int[i + 1];
                for (int j = 0; j < y[i].length; j++) {
                    if (j == 0 || j == i) {
                        y[i][j] = 1;
                    }
                    else {
                        y[i][j] = y[i - 1][j] + y[i - 1][j - 1];
                    }
                    System.out.print(y[i][j] + "\t");
                }
                System.out.println();
            }
    

    面向对象

    对象是可以接收消息的实体
    特征 :
    1.一切都是对象
    2.对象都有属性和行为
    3.每个对象都是独一无二的
    4.对象都属于某个类
    类是对象的蓝图和模板
     - 数据抽象 - 属性
     - 构造器 - 创建对象需要使用构造器
     - 行为抽象 - 方法

    面向对象编程的第1步 - 定义类

    public class Student {
        // 数据抽象 - 属性 - 找名称
        private String name;
        private int age;
        
        // 构造器
        public Student(String n, int a) {
            name = n;
            age = a;
        }
        
        // 行为抽象 - 方法 - 找动词
        public void play(String gameName) {
            System.out.println(name + "正在玩" + gameName + ".");
        }
        
        public void study() {
            System.out.println(name + "正在学习.");
        }
        
        public void watchJapaneseAV() {
            if (age >= 18) {
                System.out.println(name + "正在观看岛国爱情动作片.");
            }
            else {
                System.out.println(name + "只能观看《熊出没》.");
            }
        }
    }
    

    **面向对象编程第2步 - 创建对象 **

            // new 构造器();
            Student stu = new Student("王大锤", 15);
    

    面向对象编程第3步 - 给对象发消息

            stu.study();
            stu.play("LOL");
            stu.watchJapaneseAV();
            
            Student stu2 = new Student("张三", 18);
            stu2.study();
            stu2.play("斗地主");
            stu2.watchJapaneseAV();
    

    this 关键字

    this 代表这个对象

    • 例子:
    public class Dog {
        private String nickname;
        private boolean isLarge;
        
        public Dog(String nickname, boolean isLarge) {
            // this 代表这个对象
            this.nickname = nickname;
            this.isLarge = isLarge;
          }
    
          public void bark() {
            System.out.println(nickname + ": 汪汪汪....");
          }
        
          public void keepTheDoor() {
            if (isLarge) {
                System.out.println(nickname + "正在看门.");
            }
            else {
                System.out.println(nickname + "不能看门.");
            }
          }
       }
    

    主函数:

            Dog dog1 = new Dog("旺财", true);
            dog1.bark();
            dog1.keepTheDoor();
            
            Dog dog2 = new Dog("花花", false);
            dog2.bark();
            dog2.keepTheDoor();
    

    其他内容

    写代码的终极原则: 高内聚 低耦合
    high cohesion low coupling

    1TBS - One True Bracing Style 打{}风格
    Allman - FreeBSD

    如果定义类时没有写任何一个构造器
    那么系统会自动添加一个默认的隐式构造器(平庸构造器)

    public Clock() {
        }
    

    写代码低耦合 举例:

    System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
    

    这样写代码就跟控制台紧紧耦合在了一起 ,应该这样写:

    return String.format("%02d:%02d:%02d", hour, minute, second);
    

    窗口类

    JFrame

            // 创建窗口对象
            JFrame f = new JFrame("我的第一个窗口");
            // 通过给窗口对象发消息来设置和显示窗口
            f.setSize(400, 300); // 大小
            f.setLocationRelativeTo(null);  // 窗口摆放
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关窗口自动关闭程序
            
            Clock clock = new Clock();
            JLabel label = new JLabel(clock.display()); // 创建标签
            label.setHorizontalAlignment(JLabel.CENTER); // 设置水平对齐  - 居中
            Font font = new Font("微软雅黑", Font.BOLD, 36); // 设置字体  
            label.setFont(font); // 将字体添加到标签
            f.add(label); // 将标签添加到窗口
            
            new Timer(1000, new ActionListener() {
                
                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    clock.run();
                    label.setText(clock.display());
                }
            }).start();
            
            f.setVisible(true); // 显示窗口
    

    昨天作业讲解

    • 1.买彩票红色球 1~33    蓝色球 1~16
      01 05 11 17 18 22       05
      08 10 22 23 31 32      11
      数字不能重复
      输入 几 随机选出 几组号码
            Scanner input = new Scanner(System.in);
            System.out.print("机选几注: ");
            int n =input.nextInt();
            input.close();
            for (int counter = 1; counter <= n; counter++) {
                int[] redBalls = new int[6];
                for (int i = 0; i < redBalls.length;) {
                    // 生成1~33的随机数作为红色球的号码
                    int number = (int) (Math.random() * 33 + 1);
                    // 检查此号码在之前选中的号码中有没有出现过
                    boolean isDuplicated = false;
                    for (int j = 0; j < i; j++) {
                        if (redBalls[j] == number) {
                            isDuplicated = true;
                            break;
                        }
                    }
                    if (!isDuplicated) {
                        redBalls[i] = number;
                        i += 1;
                    }
                }
                bubbleSort(redBalls);
                for (int x : redBalls) {
                    System.out.printf("%02d ", x);
                }
                int blueBall = (int) (Math.random() * 16 + 1);
                System.out.printf("| %02d\n", blueBall);
            }
        }
        
        public static void bubbleSort(int[] array) {
            // 数组有N个数,需要N-1次循环
            boolean swapped =true;
            for (int i = 1; swapped && i < array.length; i++) {
                swapped = false;
                for (int j = 0;j < array.length - i; j++) {
                    if (array[j] > array[j + 1]) {
                        int temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                        swapped = true;
                    }
                }
            }
        }
    

    例子

    • 1.电子钟
      电子钟类:
    public class Clock {
        private int hour;
        private int minute;
        private int second;
        
        // 如果定义类时没有写任何一个构造器
        // 那么系统会自动添加一个默认的隐式构造器(平庸构造器)
    //  public Clock() {
    //  }
        
        public Clock() {
            // 拿系统时间
            // Java 7-
    //      Calendar cal = new GregorianCalendar();
    //      this.hour = cal.get(Calendar.HOUR_OF_DAY);
    //      this.minute = cal.get(Calendar.MINUTE);
    //      this.second = cal.get(Calendar.SECOND);
            
            // Java 8+
            LocalDateTime time = LocalDateTime.now();
            this.hour = time.getHour();
            this.minute = time.getMinute();
            this.second = time.getSecond();
        }
        
        public Clock(int hour, int minute, int second) {
            this.hour = hour;
            this.minute = minute;
            this.second = second;
        }
        
        public String display() {
            // 这样写代码就跟控制台紧紧耦合在了一起 
    //      System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
            return String.format("%02d:%02d:%02d", hour, minute, second);
        }
    
        public void run() {
            second += 1;
            if (second == 60) {
                second = 0;
                minute += 1;
                if (minute == 60) {
                    minute = 0;
                    hour += 1;
                    if (hour == 24) {
                        hour = 0;
                    }
                }
            }
        }
    }
    

    主函数:

            Clock clock = new Clock();
            System.out.println(clock.display());
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                clock.run();
                System.out.println(clock.display());
            }
    

    作业

    • 1.定义一个类 描述手机 品牌尺寸等 打电话 发短信等
      call send short message install application App
      uninstall / remove update

    手机类:

    public class MobilePhone {
        private String brand;
        private double size;
        private double price;
        private String phoneModel;
        private String manufacturer;
        private String number;
        
        public MobilePhone(String brand, double size, double price, String phoneModel,
                String manufacturer, String number) {
            this.brand = brand;
            this.size = size;
            this.price = price;
            this.phoneModel = phoneModel;
            this.manufacturer = manufacturer;
            this.number = number;
        }
    
        public String displayInformation() {
            return String.format("手机信息: \n品牌: " + brand + "\n型号: " + phoneModel
                    + "\n制造商: " + manufacturer + "\n尺寸: %.2f寸 \n价格: %.2f元 \n电话号码: "
                    + number, size,price);
        }
        
        public String call(String number) {
            return String.format(this.number + " 正在给 " + number + "打电话");
        }
        
        public String sendShortMessage(String number) {
            return String.format(this.number + " 正在给 " + number + "发短信");
        }
        
        public String installAPP(String app) {
            return String.format(this.phoneModel + " 正在安装 " + app);
        }
        
        public String uninstallAPP(String app) {
            return String.format(this.phoneModel + " 正在卸载 " + app);
        }
        
        public String updateAPP(String app) {
            return String.format(this.phoneModel + " 正在更新 " + app);
        }
    }
    

    主函数:

            MobilePhone mobilePhone = new MobilePhone("魅族", 5.5, 2000, "魅蓝Note",
                    "中国", "18908042994");
            System.out.println(mobilePhone.displayInformation());
            System.out.println(mobilePhone.call("18602132435"));
            System.out.println(mobilePhone.sendShortMessage("18602132435"));
            System.out.println(mobilePhone.installAPP("熊猫TV"));
            System.out.println(mobilePhone.uninstallAPP("UC浏览器"));
            System.out.println(mobilePhone.updateAPP("QQ"));
    
    • 2.写个程序 模拟 奥特曼打小怪兽
      hp mp
      攻击行为
      攻击参数 小怪兽
      奥特曼必杀技
      小怪兽反击

      奥特曼类:
    public class Ultraman {
        private String name;
        int hp;
        int mp;
        
        public Ultraman(String name, int hp, int mp) {
            this.name = name;
            this.hp = hp;
            this.mp = mp;
        }
    
        public void attack(Monster m) {
            m.hp -= 20;
            System.out.println(this.getName() + "普通攻击了" + 
            m.getName());
        }
        
        public void hugeAttack(Monster m) {
            m.hp -= 50;
            System.out.println(this.getName() + "暴击了" + 
                    m.getName());
        }
        
        public void magicalAttack(Monster[] mArray) {
            for (Monster m : mArray) {
                m.hp -= 20;
            }
            this.mp -= 100;
            System.out.println(this.getName() + "发动大招攻击了所有小怪兽");
        }
        
        public void status() {
            System.out.printf(this.getName() + " hp:%d mp:%d\n", hp, mp);
        }
        
        public String getName() {
            return this.name;
        }
    }
    

    小怪兽类:

    public class Monster {
        private String name;
        int hp;
        
        public Monster(String name, int hp) {
            this.name = name;
            this.hp = hp;
        }
        
        public void attackBack(Ultraman u) {
            u.hp -= 10;
            System.out.println(this.getName() + "反击了" + u.getName());
        }
        
        public String getName() {
            return this.name;
        }
        
        public void status() {
            System.out.printf(this.getName() + "小怪兽 hp:%d\n", hp);
        }
    }
    

    主函数:

            Ultraman ultraman = new Ultraman("迪迦奥特曼", 500, 200);
            Monster[] monsters = new Monster[3];
            for (int i = 0; i < monsters.length; i++) {
                monsters[i] = new Monster("小怪兽" + (i + 1) + "号", 100);
            }
            Scanner input = new Scanner(System.in);
            while (ultraman.hp > 0) {
                System.out.printf(ultraman.getName() + ",请选择攻击方式: \n" + "1.普通攻击  2.发动暴击 3.魔法攻击\n");
                int attackModel = input.nextInt();
                System.out.print(ultraman.getName() + ",请选择攻击哪个小怪兽: ");
                int monsterNum = input.nextInt();
                if (monsters[monsterNum - 1].hp > 0) {
                    switch (attackModel) {
                    case 1:
                        ultraman.attack(monsters[monsterNum - 1]);
                        monsters[monsterNum - 1].attackBack(ultraman);
                        ultraman.status();
                        monsters[monsterNum - 1].status();
                        break;
                    case 2:
                        ultraman.hugeAttack(monsters[monsterNum - 1]);
                        monsters[monsterNum - 1].attackBack(ultraman);
                        ultraman.status();
                        monsters[monsterNum - 1].status();
                        break;
                    case 3:
                        ultraman.magicalAttack(monsters);
                        for (int i = 0; i < monsters.length; i++) {
                            monsters[i].attackBack(ultraman);
                        }
                        ultraman.status();
                        for (int i = 0; i < monsters.length; i++) {
                            monsters[i].status();
                        }
                        break;
                    }
                }
                else {
                    System.out.println(monsters[monsterNum - 1].getName() + "没有hp了,已经死亡");
                }
            }
            input.close();
    
    • 3.改造成面向对象 围墙 过道 fencePrice aislePrice
      过道类:
    public class Aisle {
        private static final double AISLE_UNIT_PRICE = 38.5;
        private double radius;
            
        public Aisle(double radius) {
            this.radius = radius;
        }
    
        public double area() {
            return Math.PI * this.radius * this.radius;
        }
        
        public double area(double radius) {
            return Math.PI * radius * radius;
        }
        
        public double aislePrice(double r) {
            return (this.area() - area(r))* AISLE_UNIT_PRICE;
        }
    }
    

    围墙类:

    public class Fence {
        private static final double FENCE_UNIT_PRICE = 15.5;
        private double radius;
        
        public Fence(double radius) {
            this.radius = radius;
        }
    
        public double perimeter() {
            return 2 * Math.PI * this.radius; 
        }
        
        public double fencePrice() {
            return this.perimeter() * FENCE_UNIT_PRICE;
        }
    }
    

    主函数:

            Scanner input = new Scanner(System.in);
            System.out.print("请输入游泳池的半径: ");
            double r = input.nextDouble();
            if (r > 0) {
                Fence fence = new Fence(r + 3);
                System.out.printf("围墙的造价为: %.2f元\n", fence.fencePrice());
                Aisle aisle = new Aisle(r + 3);
                System.out.printf("过道的造价: %.2f元", aisle.aislePrice(r));
            }
            else {
                System.out.println("游泳池的半径应该是一个正数.");
            }
            input.close();
    

    相关文章

      网友评论

          本文标题:Java学习笔记 - 第007天

          本文链接:https://www.haomeiwen.com/subject/ljwrmttx.html