1. 程式人生 > >東文財201771010106《面向物件程式設計(java)》.18

東文財201771010106《面向物件程式設計(java)》.18

1、實驗目的與要求

(1) 綜合掌握java基本程式結構;

(2) 綜合掌握java面向物件程式設計特點;

(3) 綜合掌握java GUI 程式設計結構;

(4) 綜合掌握java多執行緒程式設計模型;

(5) 綜合程式設計練習。

2、實驗內容和步驟

任務1:填寫課程課後調查問卷,網址:https://www.wjx.cn/jq/33108969.aspx。

任務2:綜合程式設計練習

練習1:設計一個使用者資訊採集程式,要求如下:

(1) 使用者資訊輸入介面如下圖所示:

 

 

(1)使用者點選提交按鈕時,使用者輸入資訊顯示控制檯介面;

(2)使用者點選重置按鈕後,清空使用者已輸入資訊;

(3)點選視窗關閉,程式退出。

import java.awt.EventQueue;

import javax.swing.JFrame;

public class Mian {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            DemoJFrame page = new DemoJFrame();
        });
    }
}

 

 

import
java.awt.Dimension; import java.awt.Toolkit; import java.awt.Window; public class WinCenter { public static void center(Window win){ Toolkit tkit = Toolkit.getDefaultToolkit();//獲取預設工具包 Dimension sSize = tkit.getScreenSize();//獲取螢幕的大小 Dimension wSize = win.getSize();
if(wSize.height > sSize.height){ wSize.height = sSize.height; } if(wSize.width > sSize.width){ wSize.width = sSize.width; } win.setLocation((sSize.width - wSize.width)/ 2, (sSize.height - wSize.height)/ 2);//將元件移到新的位置 } }

 

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class DemoJFrame extends JFrame {
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JPanel jPanel3;
    private JPanel jPanel4;
    private JTextField fieldname;
    private JComboBox comboBox;
    private JTextField fieldadress;
    private ButtonGroup bg;
    private JRadioButton nan;
    private JRadioButton nv;
    private JCheckBox sing;
    private JCheckBox dance;
    private JCheckBox draw;

    public DemoJFrame() {
        // 設定視窗大小
        this.setSize(800, 400);
        // 設定可見性
        this.setVisible(true);
        // 設定標題
        this.setTitle("Student Detail");
        // 設定關閉操作
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        // 設定視窗居中
        WinCenter.center(this);
        // 建立四個面板物件
        jPanel1 = new JPanel();
        setJPanel1(jPanel1);
        jPanel2 = new JPanel();
        setJPanel2(jPanel2);
        jPanel3 = new JPanel();
        setJPanel3(jPanel3);
        jPanel4 = new JPanel();
        setJPanel4(jPanel4);
        // 設定容器為流式佈局
        FlowLayout flowLayout = new FlowLayout();
        this.setLayout(flowLayout);
        // 將四個面板新增到容器中
        this.add(jPanel1);
        this.add(jPanel2);
        this.add(jPanel3);
        this.add(jPanel4);

    }

    /*
     * 設定面一
     */
    private void setJPanel1(JPanel jPanel) {
        jPanel.setPreferredSize(new Dimension(700, 45));//設定此元件的首選大小
        // 給面板的佈局設定為網格佈局 一行4列
        jPanel.setLayout(new GridLayout(1, 4));
        JLabel name = new JLabel("Name:");
        name.setSize(100, 50);
        fieldname = new JTextField("");
        fieldname.setSize(80, 20);
        JLabel study = new JLabel("Qualification:");
        comboBox = new JComboBox();
        comboBox.addItem("Graduate");
        comboBox.addItem("senior");
        comboBox.addItem("Undergraduate");
        jPanel.add(name);
        jPanel.add(fieldname);
        jPanel.add(study);
        jPanel.add(comboBox);

    }

    /*
     * 設定面板二
     */
    private void setJPanel2(JPanel jPanel) {
        jPanel.setPreferredSize(new Dimension(700, 50));
        // 給面板的佈局設定為網格佈局 一行4列
        jPanel.setLayout(new GridLayout(1, 4));
        JLabel name = new JLabel("Address:");
        fieldadress = new JTextField();
        fieldadress.setPreferredSize(new Dimension(150, 50));
        JLabel study = new JLabel("Hobby:");
        JPanel selectBox = new JPanel();
        selectBox.setBorder(BorderFactory.createTitledBorder(""));
        selectBox.setLayout(new GridLayout(3, 1));
        sing = new JCheckBox("Singing");
        dance = new JCheckBox("Dancing");
        draw = new JCheckBox("Reading");
        selectBox.add(sing);
        selectBox.add(dance);
        selectBox.add(draw);
        jPanel.add(name);
        jPanel.add(fieldadress);
        jPanel.add(study);
        jPanel.add(selectBox);
    }

    /*
     * 設定面板三
     */
    private void setJPanel3(JPanel jPanel) {
        jPanel.setPreferredSize(new Dimension(700, 150));
        FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
        jPanel.setLayout(flowLayout);
        JLabel sex = new JLabel("Sex:");
        JPanel selectBox = new JPanel();
        selectBox.setBorder(BorderFactory.createTitledBorder(""));
        selectBox.setLayout(new GridLayout(2, 1));
        bg = new ButtonGroup();
        nan = new JRadioButton("Male");
        nv = new JRadioButton("Female");
        bg.add(nan);
        bg.add(nv);
        selectBox.add(nan);
        selectBox.add(nv);
        jPanel.add(sex);
        jPanel.add(selectBox);

    }

    /*
     * 設定面板四
     */
    private void setJPanel4(JPanel jPanel) {
        // TODO 自動生成的方法存根
        jPanel.setPreferredSize(new Dimension(700, 150));
        FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10);
        jPanel.setLayout(flowLayout);
        jPanel.setLayout(flowLayout);
        JButton sublite = new JButton("Validate");
        JButton reset = new JButton("Reset");
        sublite.addActionListener((e) -> valiData());
        reset.addActionListener((e) -> Reset());
        jPanel.add(sublite);
        jPanel.add(reset);
    }

    /*
     * 提交資料
     */
    private void valiData() {
        // 拿到資料
        String name = fieldname.getText().toString().trim();
        String xueli = comboBox.getSelectedItem().toString().trim();
        String address = fieldadress.getText().toString().trim();
        System.out.println(name);
        System.out.println(xueli);
        String hobbystring="";
        if (sing.isSelected()) {
            hobbystring+="Singing   ";
        }
        if (dance.isSelected()) {
            hobbystring+="Dancing   ";
        }
        if (draw.isSelected()) {
            hobbystring+="Reading  ";
        }
        System.out.println(address);
        if (nan.isSelected()) {
            System.out.println("Male");
        }
        if (nv.isSelected()) {
            System.out.println("Female");
        }
        System.out.println(hobbystring);
    }

    /*
     * 重置
     */
    private void Reset() {
        fieldadress.setText(null);
        fieldname.setText(null);
        comboBox.setSelectedIndex(0);
        sing.setSelected(false);
        dance.setSelected(false);
        draw.setSelected(false);
        bg.clearSelection();
    }
}

實驗結果:

練習2:採用GUI介面設計以下程式:

編制一個程式,將身份證號.txt 中的資訊讀入到記憶體中;

按姓名字典序輸出人員資訊;

查詢最大年齡的人員資訊;

查詢最小年齡人員資訊;

輸入你的年齡,查詢身份證號.txt中年齡與你最近人的姓名、身份證號、年齡、性別和出生地;

查詢人員中是否有你的同鄉。

輸入身份證資訊,查詢所提供身份證號的人員資訊,要求輸入一個身份證數字時,查詢介面就顯示滿足查詢條件的查詢結果,且隨著輸入的數字的增多,查詢匹配的範圍逐漸縮小。

package qq;
import java.awt.*;
import javax.swing.*;

public class ButtonTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFrame frame = new Test();
            frame.setTitle("身份證");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

 

package qq;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Test extends JFrame {
    private static ArrayList<Citizen> citizenlist;
    private static ArrayList<Citizen> list;
    private JPanel panel;
    private JPanel buttonPanel;
    private static final int DEFAULT_WITH = 600;
    private static final int DEFAULT_HEIGHT = 300;

    public Test(){
        citizenlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("E:/java/身份證號.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String temp = null;
            while ((temp = in.readLine()) != null) {

                Scanner linescanner = new Scanner(temp);

                linescanner.useDelimiter(" ");
                String name = linescanner.next();
                String id = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String birthplace = linescanner.nextLine();
                Citizen citizen = new Citizen();
                citizen.setName(name);
                citizen.setId(id);
                citizen.setSex(sex);
                int ag = Integer.parseInt(age);
                citizen.setage(ag);
                citizen.setBirthplace(birthplace);
                citizenlist.add(citizen);

            }
        } catch (FileNotFoundException e) {
            System.out.println("資訊檔案找不到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("資訊檔案讀取錯誤");
            e.printStackTrace();
        }
        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        JTextArea jt = new JTextArea();
        panel.add(jt);
        add(panel, BorderLayout.NORTH);
        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(1, 7));
        JButton jButton = new JButton("按姓名字典序輸出人員資訊");
        JButton jButton1 = new JButton("查詢年齡最大和年齡最小的人員");
        JLabel lab = new JLabel("查詢是否有你的老鄉");
        JTextField jt1 = new JTextField();
        JLabel lab1 = new JLabel("查詢年齡與你相近的人:");
        JTextField jt2 = new JTextField();
        JLabel lab2 = new JLabel("輸入你的身份證號碼:");
        JTextField jt3 = new JTextField();
        JButton jButton2 = new JButton("退出");
        jButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Collections.sort(citizenlist);
                jt.setText(citizenlist.toString());
            }
        });
        jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int max = 0, min = 100;
                int j, k1 = 0, k2 = 0;
                for (int i = 1; i < citizenlist.size(); i++) {
                    j = citizenlist.get(i).getage();
                    if (j > max) {
                        max = j;
                        k1 = i;
                    }
                    if (j < min) {
                        min = j;
                        k2 = i;
                    }

                }
                jt.setText("年齡最大:" + citizenlist.get(k1) + "年齡最小:" + citizenlist.get(k2));
            }
        });
        jButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
                System.exit(0);
            }
        });
        jt1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String find = jt1.getText();
                String text="";
                String place = find.substring(0, 3);
                for (int i = 0; i < citizenlist.size(); i++) {
                    if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place)) {
                        text+="\n"+citizenlist.get(i);
                        jt.setText("老鄉:" + text);
                    }
                }
            }
        });
        jt2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String yourage = jt2.getText();
                int a = Integer.parseInt(yourage);
                int near = agenear(a);
                int value = a - citizenlist.get(near).getage();
                jt.setText("年齡相近:" + citizenlist.get(near));
            }
        });
        jt3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                list = new ArrayList<>();
                Collections.sort(citizenlist);
                String key = jt3.getText();
                for (int i = 1; i < citizenlist.size(); i++) {
                    if (citizenlist.get(i).getId().contains(key)) {                        
                        list.add(citizenlist.get(i));                        
                        jt.setText("emmm!你可能是:\n" + list);
                    }                    
                }
            }
        });
        buttonPanel.add(jButton);
        buttonPanel.add(jButton1);
        buttonPanel.add(lab);
        buttonPanel.add(jt1);
        buttonPanel.add(lab1);
        buttonPanel.add(jt2);
        buttonPanel.add(lab2);
        buttonPanel.add(jt3);
        buttonPanel.add(jButton2);
        add(buttonPanel, BorderLayout.SOUTH);
        setSize(DEFAULT_WITH, DEFAULT_HEIGHT);
    }

    public static int agenear(int age) {
        int min = 53, value = 0, k = 0;
        for (int i = 0; i < citizenlist.size(); i++) {
            value = citizenlist.get(i).getage() - age;
            if (value < 0)
                value = -value;
            if (value < min) {
                min = value;
                k = i;
            }
        }
        return k;
    }

}

 

package qq;
public class Citizen implements Comparable<Citizen> {

    private String name;
    private String id;
    private String sex;
    private int age;
    private String birthplace;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getage() {
        return age;
    }

    public void setage(int age) {
        this.age = age;
    }

    public String getBirthplace() {
        return birthplace;
    }

    public void setBirthplace(String birthplace) {
        this.birthplace = birthplace;
    }

    public int compareTo(Citizen other) {
        return this.name.compareTo(other.getName());
    }

    public String toString() {
        return name + "\t" + sex + "\t" + age + "\t" + id + "\t" + birthplace + "\n";
    }
}

實驗結果:

按字典序輸出:

查詢最大和最小年齡:

 

查詢同鄉:

 

找年齡相近的人:

 

練習3:採用GUI介面設計以下程式

編寫一個計算器類,可以完成加、減、乘、除的操作

利用計算機類,設計一個小學生100以內數的四則運算練習程式,由計算機隨機產生10道加減乘除練習題,學生輸入答案,由程式檢查答案是否正確,每道題正確計10分,錯誤不計分,10道題測試結束後給出測試總分;

將程式中測試練習題及學生答題結果輸出到檔案,檔名為test.txt。

package counter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class Count {

    public static void main(String args[]) {
        Toolkit t = Toolkit.getDefaultToolkit();
        Dimension s = t.getScreenSize();
        EventQueue.invokeLater(() -> {
            JFrame frame = new Calculator();
            frame.setBounds(0, 0, (int) s.getWidth() / 2, (int) s.getHeight() / 2);
            frame.setTitle("計算器");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }

}

 

package counter;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import javax.swing.*;
import java.math.*;

public class Calculator extends JFrame {
    private String[] c = new String[10];
    private String[] c1 = new String[10];
    private int[] list = new int[10];
    int i = 0, i1 = 0,k=0, sum = 0;
    private PrintWriter out = null;
    private JTextArea text, text1;
    private int counter;

    public Calculator() {
        JPanel Panel = new JPanel();
        Panel.setLayout(null);
        JLabel JLabel1 = new JLabel("");
        JLabel1.setBounds(500, 800, 400, 30);
        JLabel1.setFont(new Font("Courier", Font.PLAIN, 35));
        JButton Button = new JButton("生成練習題");
        Button.setBounds(50, 150, 150, 50);
        Button.setFont(new Font("Courier", Font.PLAIN, 20));
        Button.addActionListener(new Action());
        JButton Button2 = new JButton("檢查答案");
        Button2.setBounds(300, 150, 150, 50);
        Button2.setFont(new Font("Courier", Font.PLAIN, 20));
        Button2.addActionListener(new Action1());
        JButton Button3 = new JButton("讀出檔案");
        Button3.setBounds(500, 150, 150, 50);
        Button3.setFont(new Font("Courier", Font.PLAIN, 20));
        Button3.addActionListener(new Action2());
        text = new JTextArea(30, 80);
        text.setBounds(30, 50, 200, 50);
        text.setFont(new Font("Courier", Font.PLAIN, 35));
        text1 = new JTextArea(30, 80);
        text1.setBounds(270, 50, 200, 50);
        text1.setFont(new Font("Courier", Font.PLAIN, 35));

        Panel.add(text);
        Panel.add(text1);

        Panel.add(Button);
        Panel.add(Button2);
        Panel.add(Button3);
        Panel.add(JLabel1);
        add(Panel);

    }

    private class Action implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            text1.setText("0");
            if (i < 10) {

                int a = 1 + (int) (Math.random() * 99);
                int b = 1 + (int) (Math.random() * 99);
                int m = (int) Math.round(Math.random() * 3);
                switch (m) {
                case 0:
                    while (a < b) {
                        b = (int) Math.round(Math.random() * 100);
                        a = (int) Math.round(Math.random() * 100);
                    }
                    c[i] = (i + ":" + a + "/" + b + "=");
                    list[i] = Math.floorDiv(a, b);
                    text.setText(i + ":" + a + "/" + b + "=");
                    i++;
                    break;
                case 1:
                    c[i] = (i + ":" + a + "*" + b + "=");
                    list[i] = Math.multiplyExact(a, b);
                    text.setText(i + ":" + a + "*" + b + "=");
                    i++;
                    break;
                case 2:
                    c[i] = (i + ":" + a + "+" + b + "=");
                    list[i] = Math.addExact(a, b);
                    text.setText(i + ":" + a + "+" + b + "=");
                    i++;
                    break;
                case 3:
                    while (a <= b) {
                        b = (int) Math.round(Math.random() * 100);
                        a = (int) Math.round(Math.random() * 100);
                    }
                    c[i] = (i + ":" + a + "-" + b + "=");
                    text.setText(i + ":" + a + "-" + b + "=");
                    list[i] = Math.subtractExact(a, b);
                    i++;
                    break;
                }
            }
        }
    }

    private class Action1 implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (i < 10) {
                text.setText(null);
                String daan = text1.getText().toString().trim();
                int a = Integer.parseInt(daan);
                if (text1.getText() != "") {
                    if (list[i1] == a)
                        sum += 10;
                }
                c1[i1] = daan;
                i1++;
            }
        }
    }

    private class Action2 implements ActionListener {
        public void actionPerformed(ActionEvent event) {

            try {
                out = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            for (int counter = 0; counter < 10; counter++) {
                out.println(c[counter] + c1[counter]);
            }
            out.println("成績" + sum);
            out.close();

        }

    }
}

實驗結果:

 

任務3:本學期課程已結束,請彙總《面向物件程式設計課程學習進度條》的資料,統計個人專業能力提升的資料。並從學習內容、學習方法、學習心得幾個方面進行課程學習總結,也希望你對課程的不足提出建議和意見。

 學習內容:

Java語言特點與開發環境配置(第1章、第2章)

Java基本程式結構(第3章)

Java面向物件程式結構(第4章、第5章、第6章)

 類、類間關係、類圖

Java JDK預定義類/介面及其API(String-第3章、 Arrays-第3章、Files-第3章62頁、LocalDate-第4章、 Object-第5章、物件包裝器-第5章、Comparator-第6章、 異常類-第7章、ArrayList-第5+8章、第9章、第10-12章、 第14章)    

Java異常處理程式設計模型    

Java GUI程式設計模型

Java併發程式設計(第14章)

 Java應用程式部署(第13章) 

學習方法:

老師講授知識、自主學習

(1)理論課:課前自主學習,老師總結知識,解除疑惑

(2)實驗課:通過閱讀並執行示例程式學習。和理論知識結合起來作興應當更改。課後完成老師不知道實驗作業

(3)通過老師提供分享的資料自主學習,遇到的問題找老師或助教學長解決。

實驗總結:

        經過了一學期的學習,從一開始對Java一無所知到現在可以自己編寫一些簡單的程式,我還有一些進步的,儘管進步不是很明顯,但是我也在努力,相信我會在後來的生活中會有更多的進步,感謝老師一學期來對惡我們的教導,也感謝同學們,希望大家在寒假裡過的開心,過個快樂的寒假。