• 【Java】实验代码整理(多线程、自定义异常、界面)


    1.界面+文件输入输出流

    package finalExam;
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Writer;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    
    
    public class FrameAndFile extends JFrame implements ActionListener{
        String default_save_file_name="myTxT.txt";
        
        JTextArea jTextArea;//用户输入框
        JButton jButton_read,jButton_save,jButton_clear;//两个Button
        public FrameAndFile() {
            //界面设置
            setTitle("记事本");
            Container container=getContentPane();
            container.setLayout(new BorderLayout());
            setLocation(200,300);
            
            jTextArea=new JTextArea(30,80);
            jTextArea.setLineWrap(true); //激活自动换行功能
            jTextArea.setWrapStyleWord(true);//换行不断字
            
            container.add("North",jTextArea);
            
            JPanel jPanel_button_area=new JPanel(new GridLayout(1,3));
            jButton_read=new JButton("读取");
            jButton_clear=new JButton("清空");
            jButton_save=new JButton("保存");
            jPanel_button_area.add(jButton_save);
            jPanel_button_area.add(jButton_clear);
            jPanel_button_area.add(jButton_read);
            
            jButton_clear.addActionListener(this);
            jButton_read.addActionListener(this);
            jButton_save.addActionListener(this);
            container.add("Center",jPanel_button_area);
            pack();
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            
        }
        
        public static void main(String[] args) {
            new FrameAndFile();
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            switch (e.getActionCommand()) {
            case "清空":
                jTextArea.setText("");
                break;
            case "保存":
                save();
                break;
            case "读取":
                read();
                break;
            default:
                break;
            }
            
        }
        
        /**
         * 文件读取
         * 使用FileReader+BufferedReader
         * */
        public void read() {
            FileReader fileReader=null;
            BufferedReader bufferedReader=null;
            File file=new File(default_save_file_name);
            if(file.exists()) {
                try {
                    fileReader=new FileReader(file);
                    bufferedReader=new BufferedReader(fileReader);
                    String input_str="";
                    while(bufferedReader.ready()) {
                        input_str=input_str+bufferedReader.readLine();
                    }
                    jTextArea.setText(input_str);
                } catch (FileNotFoundException e) {
                    showErrorMessage("出错了:"+e);
                    e.printStackTrace();
                } catch (IOException e) {
                    showErrorMessage("出错了:"+e);
                    e.printStackTrace();
                }finally {
                    try {
                        bufferedReader.close();
                        fileReader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                
            }else {
                showErrorMessage("文件不存在!");
            }
            
        }
        /**
         * 文件保存
         * 使用FileWriter
         * */
        public void save() {
            Writer writer=null;
            File file=new File(default_save_file_name);
            try {
                writer=new FileWriter(file,true);
                String string=jTextArea.getText();
                if(string!=null||!string.equals("")){
                    writer.write(string);
                    writer.flush();
                    showMessage("保存成功");
                }else {
                    showErrorMessage("请输入完整!");
                }
                
            } catch (IOException e) {
                showErrorMessage("出错了:"+e);
                e.printStackTrace();
            }finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
        
        public void showMessage(String message) {
            JOptionPane.showMessageDialog(null, message);
        }
        public void showErrorMessage(String message) {
            JOptionPane.showMessageDialog(null, message, "警告",
                    JOptionPane.WARNING_MESSAGE);
        }
        
    }

     2..编写选号程序,在窗体中安排6个标签,每个标签上显示0-9之间的一位数字,每位数字用一个线程控制其变化,单击“停止”按钮则所有标签数字停止变化。(多线程)

    package finalExam;
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Random;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class MultiplyThread extends JFrame{
        //自定义一个类,负责封装所有控件的操作
        RandomPanelManager randomPanelManager;
        //主类只负责界面操作
        public MultiplyThread() {
            setTitle("抽号");
            Container container=getContentPane();
            container.setLayout(new FlowLayout());
            setBounds(200,300,300,350);
            
            randomPanelManager=new RandomPanelManager();
            container.add(randomPanelManager.getCom());
    
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            
        }
        
        
        //管理类
        class RandomPanelManager implements ActionListener{
            List<MyLable> lables;//用来存放6个MyLable
            JPanel jPanel;//封装在一个大的JPanel中
            public RandomPanelManager() {
                lables=new ArrayList<MultiplyThread.MyLable>();
                jPanel=new JPanel(new GridLayout(7,1,10,10));
                for(int i=0;i<6;i++) {
                    MyLable myLable=new MyLable();
                    lables.add(myLable);
                    jPanel.add(myLable);
                }
                JPanel jPanel_buttonJPanel=new JPanel(new GridLayout(1,2));
                JButton jButton_startButton=new JButton("开始");
                JButton jButton_endButton=new JButton("停止");
                jButton_endButton.addActionListener(this);
                jButton_startButton.addActionListener(this);
                jPanel_buttonJPanel.add(jButton_startButton);
                jPanel_buttonJPanel.add(jButton_endButton);
                jPanel.add(jPanel_buttonJPanel);
            }
            public JPanel getCom() {
                return jPanel;
            }
            @Override
            public void actionPerformed(ActionEvent e) {
                switch (e.getActionCommand()) {
                case "开始":
                    start();
                    break;
                case "停止":
                    stop();
                    break;
                default:
                    break;
                }
            }
            /**
             * 开始随机数
             * 注意需要先把flag置为true
             * 再创建Thread并放入运行
             * */
            public void start() {
                for (MyLable item:lables) {
                    item.init();
                    Thread thread=new Thread(item);
                    thread.start();
                }
            }
            /**
             * 停止随机数
             * 只需要把flag置false即可
             * */
            public void stop() {
                for (MyLable item:lables) {
                    item.stop();
                }
            }
        }
        //自定义控件,实现Runnable接口
        class MyLable extends JPanel implements Runnable{
            JLabel jLabel_tag;
            boolean flag=true;
            public MyLable() {
                jLabel_tag=new JLabel("0");
                this.setLayout(new FlowLayout());
                this.add(jLabel_tag);
            }
            
            public void setText() {
                jLabel_tag.setText(getRandomNum()+"");
            }
            /**
             * 获取随机数
             * 种子为:当前时间
             * 范围[0-9]
             * */
            public int getRandomNum(){
                Date date=new Date();
                Random random=new Random(date.getTime());//随机种子
                return random.nextInt(10);
            }
    
            @Override
            public void run() {
                while(flag) {
                    setText();
                }
            }
            public void stop() {
                flag=false;
            }
            /**
             * 恢复,考虑到重复执行的情况
             * */
            public void init() {
                flag=true;
            }
        }
        
    
    
        public static void main(String[] args) {
            new MultiplyThread();
        }
    }

    3.异常处理从键盘输入一个正整数,判断是否为偶数,不是则抛出异常

    package finalExam;
    
    import java.util.Scanner;
    import java.util.regex.Pattern;
    
    public class MyException extends RuntimeException {
        
        private static final long serialVersionUID = 123456789L;
    
            public MyException() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    
        public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
            // TODO Auto-generated constructor stub
        }
    
    
        public MyException(String message, Throwable cause) {
            super(message, cause);
            // TODO Auto-generated constructor stub
        }
    
    
        public MyException(String message) {
            super(message);
            // TODO Auto-generated constructor stub
        }
    
    
        public MyException(Throwable cause) {
            super(cause);
            // TODO Auto-generated constructor stub
        }
        
        public static void main(String[] args) {
            Scanner scanner=null;
            try {
                System.out.println("请输入一个整数并继续:");
                scanner=new Scanner(System.in);
                String inputstr=scanner.nextLine();
                if(isNumeric(inputstr)) {
                    Integer a=Integer.parseInt(inputstr);
                    if(a<0) {
                        throw new MyException("不是正整数");
                    }
                    if(a%2!=0) {
                        throw new MyException("不是偶数");
                    }
                    System.out.println("输入成功!");
                }else {
                    throw new MyException("不是整数");
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                scanner.close();
            }
        }
        /**
         * 通过正则判断字符串是否为整数
         * 这个是我考虑的比较多的,可以直接不用判断
         * 在主函数中使用Scanner.nextInt
         * 如果输入不是整数会自动抛出异常
         * */
        public static boolean isNumeric(String string){
            Pattern pattern = Pattern.compile("[0-9]*");
            return pattern.matcher(string).matches();   
        }
    
    }
  • 相关阅读:
    [面试题]什么是面向对象编程
    面向对象编程的新手理解
    Object of type type is not JSON serializable
    STL---map
    STL---llist
    Div标签使用inline-block有间距
    STL---vector
    KMP算法
    算法06
    算法05
  • 原文地址:https://www.cnblogs.com/robotpaul/p/12104935.html
Copyright © 2020-2023  润新知