每日一题

<meta charset="utf-8">

面向对象的特征

  • 继承:
    继承是一种联结类的层次模型,并且允许和鼓励类的重用,它提供了一种明确表述共性的方法。对象的一个新类可以从现有的类中派生,这个过程称为类继承。新类继承了原始类的特性,新类称为原始类的派生类(子类),而原始类称为新类的基类(父类)。派生类可以从它的基类那里继承方法和实例变量,并且类可以修改或增加新的方法使之更适合特殊的需要。
  • 封装:
    封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。面向对象计算始于这个基本概念,即现实世界可以被描绘成一系列完全自治、封装的对象,这些对象通过一个受保护的接口访问其他对象。
  • 多态性:
    多态性是指允许不同类的对象对同一消息作出响应。多态性包括参数化多态性和包含多态性。多态性语言具有灵活、抽象、行为共享、代码共享的优势,很好的解决了应用程序函数同名问题。

猜数字

package com.company;

import java.util.Random;
import java.util.Scanner;

public class GuessNumber {
    public static void main(String[] args) {
        Random random = new Random();
        int number = random.nextInt(100) + 1;

        while(true){
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你要猜的数字:");
            int guessNumber = scanner.nextInt();

                if (number > guessNumber){
                    System.out.println("猜小了");
                }else if (number < guessNumber){
                    System.out.println("猜大了");
                }else{
                    System.out.println("恭喜你猜对了");
                    break;
                }
        }
    }
}

说出Entry键值对对象遍历Map集合的原理。

Map中存放的是两种对象,一种称为key(键),一种称为value(值),它们在在Map中是一一对应关系,这一对对象又称做Map 中的一个Entry(项)。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。

红包简版

package com.company.Day09.Day09_01.redbag;

public class User {

    // 用户名
    private String name;

    // 余额
    private int leftMoney;

    // 构造方法
    public User(){

    }

    public User(String name, int leftMoney) {
        this.name = name;
        this.leftMoney = leftMoney;
    }

    // get set 方法
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int getLeftMoney(){
        return leftMoney;
    }
    public void setLeftMoney(int leftMoney){
        this.leftMoney= leftMoney;
    }
    // 显示余额show方法
    public  void show(){

        System.out.println("用户" + name + "\t" + "余额为" + leftMoney);
    }
}

package com.company.Day09.Day09_01.redbag;

import java.util.ArrayList;

public class Manager extends User {

    public Manager(){

    }
    public Manager(String name,int leftMoney){
        super(name,leftMoney);
    }

    // 发红包
    public ArrayList<Integer> send(int totalMoney , int count){

        ArrayList<Integer> redList = new ArrayList<>();

        int leftMoney = super.getLeftMoney();
        // 判断
        if (totalMoney > leftMoney){
            System.out.println("余额不足");
        }

        // 扣钱
        super.setLeftMoney(leftMoney - totalMoney);

        // 每人发的钱
        int avg = totalMoney / count;
        // 除不开的钱
        int mod = totalMoney % count;

        for (int i = 0; i < count - 1; i++) {
            redList.add(avg);

        }
        int last = avg + mod;
        redList.add(last);

        return redList;

    }
}

package com.company.Day09.Day09_01.redbag;

import java.util.ArrayList;
import java.util.Random;

public class Member extends User{

    public Member(){

    }
    public Member(String name , int leftMoney){
        super(name,leftMoney);
    }

    // 收红包
    public void receive(ArrayList<Integer> list){
        Random random = new Random();
        int index = random.nextInt(list.size());
        // 收完红包后删除
        Integer removeMoney = list.remove(index);

        // 更新余额
        int leftMoney = super.getLeftMoney();
        int updateMoney = leftMoney + removeMoney;
        super.setLeftMoney(updateMoney);
    }
}

package com.company.Day09.Day09_01.redbag;

import java.util.ArrayList;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {

        Manager manager = new Manager("群主",200);
        Member one = new Member("成员1", 0);
        Member two = new Member("成员2", 0);
        Member three = new Member("成员3", 0);

//        manager.show();
//        one.show();
//        two.show();
//        three.show();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入金额");
        int money = scanner.nextInt();

        System.out.println("请输入发几个包");
        int count = scanner.nextInt();

        // 调用发红包
        ArrayList<Integer> redList = manager.send(money, count);

        // 调用收红包
        one.receive(redList);
        two.receive(redList);
        three.receive(redList);

        manager.show();
        one.show();
        two.show();
        three.show();
    }
}

简述StringBuilder类与String类的区别。

答:String类的对象内容不可改变,所以每当进行字符串拼接时,总是会在内存中创建一个新的对象,所以经常改变内容的字符串最好不要用String,因为每次生成对象都会对系统性能产生影响。
StringBuilder又称为可变字符序列,是JDK5.0中新增加的一个类,它是一个类似于String的字符串缓冲区,通过某些方法调用可以改变该序列的长度和内容。即它是一个容器,容器中可以装很多字符串,并且能够对其中的字符串进行各种操作。它的内部拥有一个数组用来存放字符串内容,进行字符串拼接时,直接在数组中加入新内容,StringBuilder会自动维护数组的扩容。

电脑模拟

package com.company.computerDemo;

public class Computer {

    public void run (){
        System.out.println("指示灯闪烁,电脑开启");
    }

    public void shutDown(){
        System.out.println("电脑关机");
    }

    public void useUSB(USB usb){
        if (usb != null){
            usb.start();
            if (usb instanceof Mouse){
                Mouse m = (Mouse) usb;
                m.click();
            }
            if (usb instanceof KeyBoard){
                    KeyBoard kb = (KeyBoard) usb;
                    kb.type();
            }

        }else{
            usb.end();
        }
    }

}

package com.company.computerDemo;

public class KeyBoard implements USB {
    @Override
    public void start() {
        System.out.println("键盘开启");
    }

    @Override
    public void end() {
        System.out.println("键盘关闭");
    }

    public void type(){
        System.out.println("疯狂输入");
    }
}

package com.company.computerDemo;

public class Mouse implements USB {
    @Override
    public void start() {
        System.out.println("鼠标开启");
    }

    @Override
    public void end() {
        System.out.println("鼠标关闭");
    }

    public void click(){
        System.out.println("疯狂点击");
    }
}

package com.company.computerDemo;

public class Test {
    public static void main(String[] args) {
        Computer c = new Computer();

        c.run();

        USB mouse = new Mouse();
        c.useUSB(mouse);

        USB keyBoard = new KeyBoard();
        c.useUSB(keyBoard);

        c.shutDown();
    }
}

package com.company.computerDemo;

public interface USB {
    public void start();
    public void end();
}

verload和Override的区别。Overloaded的方法是否可以改变返回值的类型

答:方法的重写Overriding和重载Overloading是Java多态性的不同表现。重写Overriding是父类与子类之间多态性的一种表现,重载Overloading是一个类中多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。子类的对象使用这个方法时,将调用子类中的定义,对它而言,父类中的定义如同被"屏蔽"了。如果在一个类中定义了多个同名的方法,它们或有不同的参数个数或有不同的参数类型,则称为方法的重载(Overloading)。Overloaded的方法是可以改变返回值的类型

红包界面版本

package com.company.redbag02.utils;

import java.util.ArrayList;

public interface OpenMode {
    ArrayList<Integer> divide (int totalMoney,int totalCount);
}

package com.company.redbag02.utils;

import com.company.redbag.utils.OpenMode;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 红包的框架 RedPacketFrame
 *
 * AWT / Swing / JavaFX

 */
public abstract class RedPacketFrame extends JFrame {

    private static final long serialVersionUID = 1L;

    private static final String DIR = "C:\\Users\\Liu\\Desktop\\每日一题\\2020.8.3\\Demo\\pic";

    private ArrayList<Integer> moneyList = null;

    private static int initMoney = 0;
    private static int totalMoney = 0; // 单位为“分”
    private static int count = 0;

    private static HashMap<JPanel, JLabel> panelLable = new HashMap<>();

    // 设置字体
    private static Font fontYaHei = new Font("微软雅黑", Font.BOLD, 20);
    private static Font msgFont = new Font("微软雅黑", Font.BOLD, 20);
    private static Font totalShowFont = new Font("微软雅黑", Font.BOLD, 40);
    private static Font nameFont = new Font("微软雅黑", Font.BOLD, 40);
    private static Font showNameFont = new Font("微软雅黑", Font.BOLD, 20);
    private static Font showMoneyFont = new Font("微软雅黑", Font.BOLD, 50);
    private static Font showResultFont = new Font("微软雅黑", Font.BOLD, 15);

    /**
     * 窗体大小 WIDTH:400 HEIGHT:600
     */
    private static final int FRAME_WIDTH = 416; // 静态全局窗口大小
    private static final int FRAME_HEIGHT = 650;
    private static JLayeredPane layeredPane = null;

    /// private static JPanel contentPane = null;

    /**
     * page1:输入页面 - InputPanel . 组件和初始化!
     */
    private static JPanel inputPanel = new JPanel();

    // private static JTextField input_total = new JTextField("200"); // 测试用
    // private static JTextField input_count = new JTextField("3"); // 测试用
    private static JTextField input_total = new JTextField();
    private static JTextField input_count = new JTextField();
    private static JTextField input_people = new JTextField("30");
    private static JTextField input_msg = new JTextField("恭喜发财  ,  大吉大利");
    private static JTextField input_total_show = new JTextField("$ " + input_total.getText().trim());
    private static JLabel input_inMoney = new JLabel(); // 不可见
    private static JLabel input_bg_label = new JLabel(new ImageIcon(DIR + "\\01_input.jpg"));

    static {

        // 设置位置
        input_total.setBounds(200, 90, 150, 50);
        input_count.setBounds(200, 215, 150, 50);
        input_people.setBounds(90, 275, 25, 30);
        input_msg.setBounds(180, 340, 200, 50);
        input_total_show.setBounds(130, 430, 200, 80);
        input_inMoney.setBounds(10, 535, 380, 65);
        input_bg_label.setBounds(0, 0, 400, 600); // 背景

        // 设置字体
        input_total.setFont(fontYaHei);
        input_count.setFont(fontYaHei);
        input_people.setFont(fontYaHei);
        input_msg.setFont(msgFont);
        input_msg.setForeground(new Color(255, 233, 38)); // 字体颜色 为金色
        input_total_show.setFont(totalShowFont);
        input_inMoney.setFont(fontYaHei);

        // 透明
        input_people.setOpaque(false);
        input_total_show.setOpaque(false);
        // 编 辑 -- 不可编辑
        input_people.setEditable(false);
        input_total_show.setEditable(false);

        // 边界 -- 无
        input_total.setBorder(null);
        input_count.setBorder(null);
        input_people.setBorder(null);
        input_msg.setBorder(null);
        input_total_show.setBorder(null);

    }

    /**
     * page2:打开页面 - openPanel . 组件和初始化!
     */
    private static JPanel openPanel = new JPanel();

    private static JTextField open_ownerName = new JTextField("谁谁谁");
    private static JLabel open_label = new JLabel(new ImageIcon(DIR + "\\02_open_2.gif"));
    private static JLabel open_bg_label = new JLabel(new ImageIcon(DIR + "\\02_open_1.jpg"));

    static {

        // 设置 位置.
        open_ownerName.setBounds(0, 110, 400, 50);
        open_bg_label.setBounds(0, 0, 400, 620);
        open_label.setBounds(102, 280, 200, 200);
        open_ownerName.setHorizontalAlignment(JTextField.CENTER);

        // 设置字体
        open_ownerName.setFont(nameFont);
        open_ownerName.setForeground(new Color(255, 200, 163)); // 字体颜色 为金色

        // 背景色
        // open_name.setOpaque(false);
        open_ownerName.setBackground(new Color(219, 90, 68));

        // 不可编辑
        open_ownerName.setEditable(false);
        // 边框
        open_ownerName.setBorder(null);

    }

    /**
     * page3:展示页面 - showPanel . 组件和初始化!
     */
    private static JPanel showPanel = new JPanel();
    private static JPanel showPanel2 = new JPanel();
    private static JScrollPane show_jsp = new JScrollPane(showPanel2);

    private static JLabel show_bg_label = new JLabel(new ImageIcon(DIR + "\\03_money_1.jpg"));

    private static JTextField show_name = new JTextField("用户名称");
    private static JTextField show_msg = new JTextField("祝福信息");
    private static JTextField show_money = new JTextField("99.99");
    private static JTextField show_result = new JTextField(count + "个红包共" + (totalMoney / 100.0) + "元,被抢光了");

    static {
        // 分别设置水平和垂直滚动条自动出现
        // jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        // jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        /*
         * 两部分 页面 . 1.本人获得的红包-- showPanel 2.别人获得的红包-- show_jsp
         */
        show_name.setBounds(125, 180, 100, 30);
        show_name.setOpaque(false);
        show_name.setBorder(null);
        show_name.setFont(showNameFont);

        show_msg.setBounds(0, 220, 400, 30);
        show_msg.setOpaque(false);
        show_msg.setBorder(null);
        show_msg.setFont(msgFont);
        show_msg.setHorizontalAlignment(JTextField.CENTER);

        show_money.setBounds(0, 270, 250, 40);
        show_money.setOpaque(false);
        show_money.setBorder(null);
        show_money.setFont(showMoneyFont);
        show_money.setForeground(new Color(255, 233, 38)); // 字体颜色 为金色
        show_money.setHorizontalAlignment(SwingConstants.RIGHT);

        show_result.setBounds(10, 460, 400, 20);
        show_result.setOpaque(false);
        show_result.setBorder(null);
        show_result.setFont(showResultFont);
        show_result.setForeground(new Color(170, 170, 170)); // 字体颜色 为灰色

        // 设置 图片.
        show_bg_label.setBounds(0, 0, 400, 500);

    }

    static {

        // 页面和 背景的对应关系.
        panelLable.put(inputPanel, input_bg_label);
        panelLable.put(openPanel, open_bg_label);
        panelLable.put(showPanel, show_bg_label);
    }

    private void init() {
        // 层次面板-- 用于设置背景
        layeredPane = this.getLayeredPane();
//        System.out.println("层次面板||" + layeredPane);
        // System.out.println(layeredPane);

        // 初始化框架 -- logo 和基本设置
        initFrame();
        // 初始化 三个页面 -- 准备页面
        initPanel();

        // 2.添加 页面 --第一个页面, 输入 panel 设置到 页面上.
        setPanel(inputPanel);

        // 3.添加 监听
        addListener();
    }

    /**
     * 初始化框架 -- logo 和基本设置
     */
    private void initFrame() {
        // logo
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(DIR + "\\logo.gif"));
//        System.out.println("LOGO初始化...");

        // 窗口设置
        this.setSize(FRAME_WIDTH, FRAME_HEIGHT); // 设置界面大小
        this.setLocation(280, 30); // 设置界面出现的位置
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(null);

        // 测试期 注释 拖 拽 , 运行放开
        // this.setResizable(false);
        this.setVisible(true);
    }

    /**
     * 初始化页面-- 准备三个页面
     */

    private void initPanel() {
//        System.out.println("页面初始化...");
        initInputPanel();
        initOpenPanel();
        initShowPanel();

    }

    private void initInputPanel() {

        inputPanel.setLayout(null);
        inputPanel.setBounds(0, -5, 400, 600);

        // this.add(bg_label);
        inputPanel.add(input_total);
        inputPanel.add(input_count);
        inputPanel.add(input_people);
        inputPanel.add(input_msg);
        inputPanel.add(input_total_show);
        inputPanel.add(input_inMoney);

//        System.out.println("输入页面||" + inputPanel);

    }

    private void initOpenPanel() {
        openPanel.setLayout(null);
        openPanel.setBounds(0, 0, 400, 600);
        // this.add(bg_label);
        openPanel.add(open_ownerName);
        openPanel.add(open_label);
//        System.out.println("打开页面||" + openPanel);
    }

    private void initShowPanel() {
        showPanel.setLayout(null);
        showPanel.setBounds(10, 10, 300, 600);

        // ==============
        showPanel.add(show_name);
        showPanel.add(show_msg);
        showPanel.add(show_money);
        showPanel.add(show_result);
//        System.out.println("展示页面||" + showPanel);
        // ====================================
        // showPanel2.setLayout(null);
        // showPanel2.setBounds(0, 500, 401, 300);

        showPanel2.setPreferredSize(new Dimension(300, 1000));
        showPanel2.setBackground(Color.white);

        show_jsp.setBounds(0, 500, 400, 110);

    }

    /**
     * 每次打开页面, 设置 panel的方法
     */
    private void setPanel(JPanel panel) {
        // 移除当前页面
        layeredPane.removeAll();

//        System.out.println("重新设置:新页面");
        // 背景lable添加到layeredPane的默认层
        layeredPane.add(panelLable.get(panel), JLayeredPane.DEFAULT_LAYER);

        // 面板panel设置为透明
        panel.setOpaque(false);

        // 面板panel 添加到 layeredPane的modal层
        layeredPane.add(panel, JLayeredPane.MODAL_LAYER);
    }

    // private void setShowPanel(JPanel show) {
    // setPanel(show);
    // layeredPane.add(show_jsp, JLayeredPane.MODAL_LAYER);
    //
    // }

    /**
     * 设置组件的监听器
     */
    private void addListener() {

        input_total.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                // System.out.println(e);
                String input_total_money = input_total.getText();
                input_total_show.setText("$ " + input_total_money);
            }
        });

        input_count.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                // System.out.println(e);
//                System.out.println("个数:" + input_count.getText());
            }
        });
        input_msg.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                // System.out.println(e);
//                System.out.println("留言:" + input_msg.getText());
            }
        });

        input_inMoney.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {

                    // 获取页面的值.
                    totalMoney = (int) (Double.parseDouble(input_total.getText()) * 100); // 转换成"分"
                    count = Integer.parseInt(input_count.getText());
                    if (count > 30) {
                        JOptionPane.showMessageDialog(null, "红包个数不得超过30个", "红包个数有误", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }

                    initMoney = totalMoney;

                    System.out.println("总金额:[" + totalMoney + "]分");
                    System.out.println("红包个数:[" + count + "]个");

                    input_inMoney.removeMouseListener(this);

//                    System.out.println("跳转-->打开新页面");

                    // 设置群主名称
                    open_ownerName.setText(ownerName);
                    // 设置打开页面
                    setPanel(openPanel);

                } catch (Exception e2) {
                    JOptionPane.showMessageDialog(null, "请输入正确【总金额】或【红包个数】", "输入信息有误", JOptionPane.ERROR_MESSAGE);

                }
            }
        });

        // open_ownerName ,点击 [名称],触发的方法 , 提示如何设置群主名称.

        open_ownerName.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                JOptionPane.showMessageDialog(null, "请通过【setOwnerName】方法设置群主名称", "群主名称未设置",
                        JOptionPane.QUESTION_MESSAGE);
            }
        });

        // open label , 点击 [开],触发的方法,提示如何设置打开方式.
        open_label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (openWay == null) {
                    JOptionPane.showMessageDialog(null, "请通过【setOpenWay】方法设置打开方式", "打开方式未设置",
                            JOptionPane.QUESTION_MESSAGE);
                    return;
                }

//                System.out.println("跳转-->展示页面");

                moneyList = openWay.divide(totalMoney, count);

//                System.out.println(moneyList);
                /*
                 * showPanel 添加数据
                 *
                 */
                show_name.setText(ownerName);
                show_msg.setText(input_msg.getText());
                if (moneyList.size() > 0) {
                    show_money.setText(moneyList.get(moneyList.size() - 1) / 100.0 + "");
                }
                show_result.setText(count + "个红包共" + (initMoney / 100.0) + "元,被抢光了");

                open_label.removeMouseListener(this);

                setPanel(showPanel);

                // 添加数据
                for (int i = 0; i < moneyList.size(); i++) {

                    JTextField tf = new JTextField();
                    tf.setBorder(null);
                    tf.setFont(showNameFont);
                    tf.setHorizontalAlignment(JTextField.LEFT);
                    if (i == moneyList.size() - 1) {
                        tf.setText(ownerName + ":\t" + moneyList.get(i) / 100.0 + "元");

                    } else {

                        tf.setText("群成员-" + i + ":\t" + moneyList.get(i) / 100.0 + "元");
                    }
                    showPanel2.add(tf);
                }

                layeredPane.add(show_jsp, JLayeredPane.MODAL_LAYER);
            }

        });

    }

    /* ======================================================================
     * **********************************************************************
     * * 以上代码均为页面部分处理,包括布局/互动/跳转/显示等,大家                         *
     * *                                                                    *
     * *                                                                    *
     * **********************************************************************
     * ======================================================================
     */

    /**
     * 1.ownerName 群主名称
     */

    private String ownerName = "爱谁谁";

    /**
     * openWay 红包类型 【普通红包,手气红包】
     */

    private OpenMode openWay = null;

    // 构造方法
    // title界面的标题

    public RedPacketFrame(String title) throws HeadlessException {
        super(title);
        // 页面相关初始化
        init();
    }

    // 生成ownerName 和 OpenWay的set方法

    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public void setOpenWay(OpenMode openWay) {
        this.openWay = openWay;
    }
}

package com.company.redbag02;

import com.company.redbag02.utils.RedPacketFrame;

import java.awt.*;

public class MyRed extends RedPacketFrame {
    public MyRed(String title) throws HeadlessException {
        super(title);
    }
}

package com.company.redbag02;

import com.company.redbag.utils.OpenMode;

import java.util.ArrayList;
import java.util.Random;

public class NurtalDemo implements OpenMode {

    @Override
    public ArrayList<Integer> divide(int totalMoney, int totalCount) {

        ArrayList<Integer> list = new ArrayList<>();

        int avg = totalMoney / totalCount;
        int mod = totalMoney % totalCount;

        for (int i = 0; i < totalCount - 1; i++) {

            list.add(avg);
        }

        list.add(avg + mod);

        return list;
    }
}

package com.company.redbag02;

import com.company.redbag.utils.OpenMode;

import java.util.ArrayList;
import java.util.Random;

public class RandomDemo implements OpenMode {
    @Override
    public ArrayList<Integer> divide(int totalMoney, int totalCount) {
        ArrayList<Integer> list = new ArrayList<>();

        Random random = new Random();
        int leftMoney = totalMoney;
        int leftCount = totalCount;

        for (int i = 0; i < totalCount - 1; i++) {
            int money = random.nextInt(totalMoney / totalCount * 2) + 1;

            list.add(money);

            leftCount--;
            leftMoney -= money;

        }

        list.add(leftMoney);

        return list;
    }
}

package com.company.redbag02;

import com.company.redbag.MyRed;
import com.company.redbag.RandomMode;

public class Test {
    public static void main(String[] args) {
        MyRed myRed = new MyRed("强强强");
        myRed.setOwnerName("小强");

        RandomMode randomMode = new RandomMode();
        myRed.setOpenWay(randomMode);
    }
}

final可以修饰的元素:

  • 类:不能被继承
  • 变量(属性和局部变量):不能被重新赋值 ,在声明时赋值或在构造器中赋值, 系统不对final属性默认的赋初始值
  • 方法:不能在子类中被覆盖,即不能修改。

扑克简版

package com.company;

import java.util.ArrayList;
import java.util.Collections;

public class DEMO01 {
    public static void main(String[] args) {
        ArrayList<String> pokerBox = new ArrayList<>();
        ArrayList<String> colors = new ArrayList<>();
        ArrayList<String> numbers = new ArrayList<>();

        colors.add("♥");
        colors.add("♦");
        colors.add("♣");
        colors.add("♠");

        for (int i = 2; i <= 10; i++) {
            numbers.add(i + "");

        }
        numbers.add("A");
        numbers.add("K");
        numbers.add("Q");
        numbers.add("J");

        for (String color:colors){
            for(String number:numbers){
                String s = color + number;
                pokerBox.add(s);
            }
        }

        pokerBox.add("大王");
        pokerBox.add("小王");

        Collections.shuffle(pokerBox);

        ArrayList<String> player1 = new ArrayList<>();
        ArrayList<String> player2 = new ArrayList<>();
        ArrayList<String> player3 = new ArrayList<>();
        ArrayList<String> dipai = new ArrayList<>();

        for (int i = 0; i < pokerBox.size(); i++) {
            String s = pokerBox.get(i);

            if (i >= 51){
                dipai.add(s);

            }else if (i % 3 == 0){
                player1.add(s);
            }else if (i % 3 == 1){
                player2.add(s);
            }else {
                player3.add(s);
            }
        }

        System.out.println(player1);
        System.out.println(player2);
        System.out.println(player3);
        System.out.println(dipai);
    }
}

this关键字

  • 定义: 代表对象自身的引用,通常在类的方法定义中使用。
  • 用this关键字的情况:
    • 方法中的变量与成员变量重名
    • 在一个构造器中调用其它重载的构造器
    • 返回当前对象的引用

扑克增强版

package com.company;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
        // 创建一个map集合存放扑克牌
        HashMap<Integer, String> map = new HashMap<>();

        ArrayList<String> colors = new ArrayList<>();
        Collections.addAll(colors,"♥","♦","♣","♠");
        ArrayList<String> numbers = new ArrayList<>();
        Collections.addAll(numbers,"3","4","5","6","7","8","9","10",
                "J","Q","K","A","2");

        int count = 1;
        for(String number:numbers){
            for (String color:colors){
                String s = color + number;
                map.put(count++,s);

            }
        }
        map.put(count++,"大王");
        map.put(count++,"小王");

        Set<Integer> set = map.keySet();
        ArrayList<Integer> list = new ArrayList<>();
        list.addAll(set);
        Collections.shuffle(list);

        ArrayList<Integer> noP1 = new ArrayList<>();
        ArrayList<Integer> noP2 = new ArrayList<>();
        ArrayList<Integer> noP3 = new ArrayList<>();
        ArrayList<Integer> noDiPai = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            if (i >= 51){
                noDiPai.add(list.get(i));
            }else if (i % 3 == 0){
                noP1.add(list.get(i));
            }else if (i % 3 == 1){
                noP2.add(list.get(i));
            }else{
                noP3.add(list.get(i));
            }
        }

        Collections.sort(noP1);
        Collections.sort(noP2);
        Collections.sort(noP3);
        Collections.sort(noDiPai);

        ArrayList<String> player1 = new ArrayList<>();
        ArrayList<String> player2 = new ArrayList<>();
        ArrayList<String> player3 = new ArrayList<>();
        ArrayList<String> dipai = new ArrayList<>();

        for (Integer p1:noP1){
            player1.add(map.get(p1));
        }
        for (Integer p2:noP2){
            player2.add(map.get(p2));
        }
        for (Integer p3:noP3){
            player3.add(map.get(p3));
        }
        for (Integer p4:noDiPai){
            dipai.add(map.get(p4));
        }

        System.out.println(player1);
        System.out.println(player2);
        System.out.println(player3);
        System.out.println(dipai);

    }
}

作用域public,private,protected,以及不写时的区别

image

兔子问题

古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子, 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问前10个月每个月的兔子对数为多少?

public class Demo01_02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入月份:");
        int n = scanner.nextInt();
        System.out.println("第"+n+"个月兔子有"+fun(n)+"对");
    }
    private static int fun(int n){
        if (n==1 || n==2){
            return  1;
        }else{
            return fun(n-1)+fun(n-2);
        }
    }
}

public class Demo01_01 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查的月份:");
        int i1 = scanner.nextInt();
        int a = 1 ;
        System.out.println("第1个月兔子有"+a+"对");
        int b = 1 ;
        System.out.println("第2个月兔子有"+b+"对");
        int c;
        for (int i = 3; i <= i1; i++) {
               c = a ;
               a =a + b;
               b = c;
            System.out.println("第"+i+"个月兔子有"+a+"对");

            }

        }

    }

素数

题目:判断101-200之间有多少个素数,并输出所有素数。
程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),
如果能被整除,则表明此数不是素数,反之是素数。

package com.company.chongchongchong;

/**
 * 题目:判断101-200之间有多少个素数,并输出所有素数。
 * 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),
 * 如果能被整除,则表明此数不是素数,反之是素数。
 */
public class Demo02_01 {
    public static void main(String[] args) {
        int count = 0;
         A:for (int i = 101; i <=200 ; i++) {

            for (int j = 2;j<= Math.sqrt(i);j++){
                if (i%j==0){
                    continue A;
                }
            }
            count++;
        }
        System.out.println("素数共有"+count+"个");
    }
}

水仙花数

题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

public class Demo03_01 {
    public static void main(String[] args) {

        for (int i = 100; i < 1000; i++) {
            int ge = i % 10;
            int shi = i % 100 / 10;
            int bai = i / 100;

            if (ge*ge*ge + shi*shi*shi + bai*bai*bai == bai*100 + shi*10 + ge ){
                System.out.println(i+"是水仙花数");
            }
        }
    }
}

正整数分解质因数

题目:将一个正整数分解质因数。例如:输入90,打印出90=233*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。

public class Demo04_01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个正整数:");
        int i = scanner.nextInt();
        System.out.print(i+"=");
        for (int j = 2; j <= i; j++) {
            while (i%j == 0 && i!=j){
                i = i/j;
                System.out.print(j+"*");

            }
            if (i == j){
                System.out.print(i);
                break;
            }

        }

    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354