当前位置: 首页 > news >正文

网路编程---实验1 Java I/O和Java线程应用

实验1 Java I/O和Java线程应用

1.实现内容

1)搭建java运行环境

2)Java IO流的用法

3)Java线程

2.实验步骤

1.完成以下程序。

第一题:利用Java输入输出流编程实现计算器。

功能

(1)先输入第一组操作数,并将其存放在一个文件中。

(2)然后输入第二组操作数,并将其存放在第二个文件中。

(3)选择一种加减乘除运算。

(4)从第一个文件中取第一个操作数,从第二个文件中取第二个操作数,将其按照第三步中选择的运算做加减乘除后存入到第三个文件中。

(5)从第三个文件中读取出运算结果。

其他要求:

(1)要求处理double型或float型数据。

(2)能够处理程序运行结果中的各种异常。

2.完成以下程序。

第二题:利用Java多线程机制实现带闪动字幕的时钟。

功能

(1)当用户在“命令”后的文本框中输入“start clock”后,“现在的时间是”后的文本框开始显示系统时钟;当用户输入“stop clock”后,时钟终止显示。

(2)当用户在“命令”后的文本框中输入“fast”后,能够加速字幕的闪动(字幕循环地有小变大,然后再变小);输入“slow”后,能够减慢字幕闪动;输入“stop”后,闪动字幕停止;输入“restart”后,字幕重新开始闪动;

(3)当用户在“命令”后的文本框中输入“change ”+字符串时,可更改字幕显示内容。如,输入“change 我可爱的小时钟”后,字幕变为“我可爱的小时钟”。

3.实验结果

3.1第一问-输入输出流

package test;


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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

        operate();
    }
    //设置需要进行的操作
    public static void operate(){
        Scanner sc=new Scanner(System.in);
        boolean flag=true;
        //默认是循环执行的
        while (flag){
            System.out.println("请输入您要选择的操作〔请输民1--4中的任一数字):");
            System.out.println("1:输入第一组操作数");
            System.out.println("2:输入第二组操作数");
            System.out.println("3:进行运算");
            System.out.println("4:退出系统");
            String temp=sc.nextLine();
            //对输入的信息进行判断
            switch (temp){
                case "1":
                    //读取数字a的信息
                    saveNum(1,"num1.txt");
                    break;
                case "2":
                    //读取数字b的信息
                    saveNum(2,"num2.txt");
                    break;
                    //运算操作
                case "3":
                    calculationOperation();
                    break;
                case "4":
                    flag=false;
                    System.out.println("退出成功!");
                    break;
                default:
                    System.out.println("无效操作!");
            }
            //switch分支

        }

        //关闭
//        sc.close();
    }


    /*
    * 运算操作
    * */
    public static void calculationOperation(){
        Scanner sc=new Scanner(System.in);
        List<Double> a=new ArrayList();
        List<Double> b=new ArrayList();

        //要进行的操作
        String operator="";
        boolean flag=true;
        while (flag){
            System.out.println("请输入您要进行的操作(输入1--4中的任何一个数字)");
            System.out.println("1:加法");
            System.out.println("2:减法");
            System.out.println("3:乘法");
            System.out.println("4:除法");
            System.out.println("5:返回上一级");
            operator=sc.next();
            switch (operator){
                case "1":
                    operator="+";
                    break;
                case "2":
                    operator="-";
                    break;
                //运算操作
                case "3":
                    operator="*";
                    break;
                case "4":
                    operator="/";
                    break;
                case "5":
                    flag=false;
                    break;
                default:
                    System.out.println("无效操作!");
            }
            //确保每一步的操作都是正确的
            if (flag&&(
                    operator.equals("+")||
                            operator.equals("-")||
                            operator.equals("*")||
                            operator.equals("/")
                    )){
                //要进行的操作 end

                //读取文件中的信息,将文件中的信息输入到对应的数组中去
                BufferedReader r1=null;
                BufferedReader r2=null;
              try {
                  File num1=new File("自己的路径num1.txt");
                   r1=new BufferedReader(new FileReader(num1));
                   File num2=new File("自己的路径num2.txt");
                   r2=new BufferedReader(new FileReader(num2));
                  String str="";
                  a.clear();
                  b.clear();
                  while ((str=r1.readLine())!=null){
                      a.add(Double.parseDouble(str.trim()));
                  }
                  while ((str=r2.readLine())!=null){
                      b.add(Double.parseDouble(str.trim()));
                  }
                  r1.close();
                  r2.close();
              }
              catch (IOException x){
                  System.out.println("error:找不到文件!");
                  flag=false;
              }
              finally {
                  try {
                      r1.close();
                      r2.close();
                  } catch (IOException e) {
                      System.out.println("error:关闭资源出现错误!");
                  }

              }
                //获取要循环遍历的数组的大小
                int count=a.size()>b.size()?a.size():b.size();

                //计算文件中的信息
                try {
                    System.out.println("最终的运算的结果是:");

                    //将信息写入到文件中去========
                    File result=new File("自己的路径result.txt");
                    BufferedWriter writer=new BufferedWriter (new FileWriter(result));;
                    //先删除
                    if (result.exists()){
                        result.delete();
                    }
                    //再创建
                    if (!result.exists()){
                        result.createNewFile();
                    }
                    //循环进行计算
                    for (int i = 0; i <count ; i++) {
                        Double temp=arithmetiCoperation(a.get(i),b.get(i),operator);
                        System.out.println("第"+i+"个:"+temp);
                        writer.write(temp+"");
                        writer.newLine();
                    }

                    writer.flush();
                    writer.close();
                }

                catch (Exception e){
                    System.out.println("error:出现异常!请检查文件中的数据是不是正确的!");
                    System.out.println("error:异常信息为,"+e);
                }
            }
        }
//        sc.close();
    }
    /*
    * 运算操作
    * operator 运算符
    * */
    public static Double arithmetiCoperation(double a,double b,String operator){
        Double result=null;
        //进行算数运算操作
       try {
           switch (operator){
               case "+":
                   result=a+b;
                   break;
               case "-":
                   result=a-b;
                   break;
               case "*":
                   result=a*b;
                   break;
               case "/":
                   result=a/b;
                   break;
           }
       }
       //捕获异常
       catch (Exception e){
            result=null;
       }
        return result;
    }
    /*
    * 往指定的文件的名称中加入信息
    * f 指定哪个文件数字1和2
    * 地址已经指定好
    * */
    public static void saveNum(int f,String path){
        Scanner scx=new Scanner(System.in);
        File file=new File("自己的路径"+path);
        BufferedWriter bufferedWriter=null;
        try {
            bufferedWriter=new BufferedWriter(new FileWriter(file));
           if (file.exists()){
               file.delete();
           }
           if (!file.exists()){
               file.createNewFile();
           }
            boolean flag=true;
            System.out.println("开始向文件"+f+"输入第"+f+"组数据");
            //要输入的字符的信息
            String temp="";
           while (flag){
               System.out.println("请输入操作数(请输入end或END结束输入)");
               temp= scx.next();
                if (!temp.equalsIgnoreCase("end")){
                   try{
                       bufferedWriter.write(Double.parseDouble(temp)+"");
                       bufferedWriter.newLine();
                   }
                   catch (Exception e){
                        System.out.println("数字格式不对!");
                   }
                }
                else {
                    bufferedWriter.flush();
                    flag=false;
                }
           }

       }
       catch (Exception e){
            System.out.println("error:写入num的时候出现错误!");
       }
       finally {
            //退出循环
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                System.out.println("error:close资源对象失败!");
            }
//            scx.close();
        }
    }

}

效果图:

 

 

3.2第二问-多线程-左右滑动字幕(方式1)

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ScrollingAndDictAndTimer extends JFrame {

	//显示的是输入框
	JTextField textOfCommond, textOfTimer;
	//显示的是label
	JLabel labelOfCommond, labelOfTimer, labelOfScrollWords,
			labelOfBlank;

	boolean stopScrolling=false, stopTimer=true;
	// 是否停止滚动标志位,是否停止显示系统时间标志位
	int sleeptime =1000;
	Thread scrollWordsThread, timerThread;
	scrollThread sth_obj;
	timerThread tth_obj;
	public ScrollingAndDictAndTimer()
	{
		super();
		this.setTitle("一个带滚动字幕和时钟的小字典");

		//显示的是当前的时间的信息
		labelOfTimer = new JLabel("现在的时间是");
		textOfTimer = new JTextField(14);
		JPanel jp1 = new JPanel(new FlowLayout());
		jp1.add(labelOfTimer);
		jp1.add(textOfTimer);

		//显示的是当前要输入的指令的信息
		labelOfCommond = new JLabel("命令:");
		textOfCommond = new JTextField(14);

		JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
		jp2.add(labelOfCommond);
		jp2.add(textOfCommond);

		//设置滚动的文字
		labelOfScrollWords = new JLabel("欢迎使用本系统!");
		JPanel jp3 = new JPanel(new FlowLayout());
		jp3.add(labelOfScrollWords);

		//设置指令的事件监听
		textOfCommond.addActionListener(new textFieldActionListener());

		//设置界面的布局基本信息
		this.setLayout(new GridLayout(3,1));
		this.setBounds(100, 100, 450, 200);
		this.add(jp1);
		this.add(jp2);
		this.add(jp3);

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);

		//线程的信息
		tth_obj = new timerThread();
		sth_obj = new scrollThread();
		//滚动字幕的线程
		scrollWordsThread = new Thread(sth_obj);
		timerThread = new Thread(tth_obj);

		scrollWordsThread.start();
//		timerThread.start();

	}
	private class textFieldActionListener implements ActionListener{
		public void actionPerformed(ActionEvent e)
		{
			if(e.getSource()==textOfCommond)
			{
				String str = textOfCommond.getText().trim();//提取用户在左侧文本框中的输入
				if (str.equalsIgnoreCase("fast")) {
					//加速滚动
					//scrollWordsThread.interrupt();
					sleeptime=sleeptime/2;
				}
				else if (str.equalsIgnoreCase("slow")) {
					//加速滚动
					//scrollWordsThread.interrupt();
					sleeptime=sleeptime*2;
				}

				else if (str.equalsIgnoreCase("stop")) {
					//停止滚动
					stopScrolling = true;
				} else if (str.equalsIgnoreCase("restart")) {
					//重新开始滚动
				if (!scrollWordsThread.isAlive()) {
						// 判定线程是否已经死亡(是否还占有实体)

						scrollWordsThread = new Thread(sth_obj);// 给线程分配实体
						stopScrolling = false;
						scrollWordsThread.start();// 启动线程
					}
				} else if (str.equalsIgnoreCase("start clock")) {
					//启动时钟线程
					if (!timerThread.isAlive()) {
						// 判定timerThread是否已经进入死亡状态
						timerThread = new Thread(tth_obj);
						stopTimer = false;
						timerThread.start();
//						textOfChinese.setText("启动时钟");
					}
				}else if(str.equalsIgnoreCase("stop clock")){//停止时钟线程
					stopTimer = true;//将”停止显示时间“标志位设置为true
//					textOfChinese.setText("停止时钟");
				}
				else if(str.matches("^change.*")){//停止时钟线程
					System.out.println(str);
					String temp="";
					try {
						temp=str.split("change")[1].trim();
					}
					catch (Exception x){
						temp="欢迎使用本系统!";
					}
					labelOfScrollWords.setText(temp);
				}
				else{
//					textOfChinese.setText("没有这个单词的英文翻译!");
				}

			}
		}
	}
	//滚动字幕的线程的信息
	private class scrollThread implements Runnable{
		//重写的方法
		@Override
		public void run()
		{
			while (true) {
				//获取坐标值
				int x = labelOfScrollWords.getBounds().x;
				int y = labelOfScrollWords.getBounds().y;
				x += 5;
				//设置显示的位置的信息
				labelOfScrollWords.setLocation(x, y);
				if (x > 380) {
					x = 10;
					labelOfScrollWords.setLocation(x, y);
				}
				try {
					//Thread.sleep(1000);
					Thread.sleep(sleeptime);
				} catch (InterruptedException ex) {
				}
				if (stopScrolling==true) {//如果“stop”,线程终止
					return;
				}
			}
		}
	}
	private class timerThread implements Runnable{
		public void run()
		{
			while (!stopTimer) {
				Date date = new Date();
				String str = date.toString().substring(11, 19);
				//System.out.println(date.toString());
				// 把date中的時間提取出来
				textOfTimer.setText(str);// 把时间显示在文本框中
				try {
					Thread.sleep(1000);// 休眠1000毫秒
				} catch (InterruptedException ex) {
				}
				/*if (stopTimer == true) {
					return;
					// 如果输入了“stop clock”,线程timerThread停止返回
				}*/
			}
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ScrollingAndDictAndTimer sdt = new ScrollingAndDictAndTimer();
		sdt.setVisible(true);

	}

}

效果图

3.3第二问-多线程-闪动字幕(方式2)

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

/*
 * 设置滚动的字幕
 * */
public class ScrollingAndDictAndTimer extends JFrame {

    /*
     * textOfCommond,显示指令
     *textOfTimer,显示时间
     * */
    JTextField textOfCommond, textOfTimer;
    /*
     * label
     * labelOfCommond 指令
     * labelOfTimer 时间
     * labelOfScrollWords 滚动的字幕
     * */
    JLabel labelOfCommond, labelOfTimer, labelOfScrollWords;
    /*
     * stopScrolling 停止的标志
     * stopTimer 时间停止的标志
     * */
    boolean stopScrolling = false, stopTimer = true;
    /*
     * 滚动的时间
     * */
    int sleeptime = 1000;
    /*
     * 线程
     * scrollWordsThread 设置滚动字幕的线程
     * timerThread 设置时间的定时器
     * */
    Thread scrollWordsThread, timerThread;
    scrollThread sth_obj;
    timerThread tth_obj;
    //定时器,用于设置字母的大小变换
    private Timer timer = null;

    /*
     * 界面框的代码
     * */
    public ScrollingAndDictAndTimer() {
        super();
        this.setTitle("一个带滚动字幕和时钟的小字典");
        //显示的是当前的时间的信息
        //设置第一行的信息
        labelOfTimer = new JLabel("现在的时间是");
        textOfTimer = new JTextField(14);
        JPanel jp1 = new JPanel(new FlowLayout());
        jp1.add(labelOfTimer);
        jp1.add(textOfTimer);

        //显示的是当前要输入的指令的信息
        labelOfCommond = new JLabel("命令:");
        textOfCommond = new JTextField(14);

        JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
        jp2.add(labelOfCommond);
        jp2.add(textOfCommond);

        //设置滚动的文字
        labelOfScrollWords = new JLabel("欢迎使用本系统!");
        JPanel jp3 = new JPanel(new FlowLayout());
        jp3.add(labelOfScrollWords);

        //设置指令的事件监听
        textOfCommond.addActionListener(new textFieldActionListener());

        //设置界面的布局基本信息
        this.setLayout(new GridLayout(3, 1));
        this.setBounds(100, 100, 450, 200);
        this.add(jp1);
        this.add(jp2);
        this.add(jp3);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        //线程的信息
        tth_obj = new timerThread();
        sth_obj = new scrollThread();
        //滚动字幕的线程
        scrollWordsThread = new Thread(sth_obj);
        timerThread = new Thread(tth_obj);
        scrollWordsThread.start();

    }

    public static void main(String[] args) {
        ScrollingAndDictAndTimer sdt = new ScrollingAndDictAndTimer();
        sdt.setVisible(true);
    }

    private class textFieldActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == textOfCommond) {
                String str = textOfCommond.getText().trim();//提取用户在左侧文本框中的输入
                if (str.equalsIgnoreCase("fast")) {
                    //加速滚动
                    //scrollWordsThread.interrupt();
                    sleeptime = sleeptime / 2;
                    timer.setDelay(sleeptime);

                } else if (str.equalsIgnoreCase("slow")) {
                    //加速滚动
                    sleeptime = sleeptime * 4;
                    timer.setDelay(sleeptime);

                } else if (str.equalsIgnoreCase("stop")) {
                    //停止滚动
                    stopScrolling = true;
                } else if (str.equalsIgnoreCase("restart")) {
                    //重新开始滚动
                    if (!scrollWordsThread.isAlive()) {
                        // 判定线程是否已经死亡(是否还占有实体)
                        scrollWordsThread = new Thread(sth_obj);// 给线程分配实体
                        stopScrolling = false;
                        scrollWordsThread.start();// 启动线程
                    }
                } else if (str.equalsIgnoreCase("start clock")) {
                    //启动时钟线程
                    if (!timerThread.isAlive()) {
                        // 判定timerThread是否已经进入死亡状态
                        timerThread = new Thread(tth_obj);
                        stopTimer = false;
                        timerThread.start();
//						textOfChinese.setText("启动时钟");
                    }
                } else if (str.equalsIgnoreCase("stop clock")) {//停止时钟线程
                    stopTimer = true;//将”停止显示时间“标志位设置为true
//					textOfChinese.setText("停止时钟");
                } else if (str.matches("^change.*")) {//停止时钟线程
                    System.out.println(str);
                    String temp = "";
                    try {
                        temp = str.split("change")[1].trim();
                    } catch (Exception x) {
                        temp = "欢迎使用本系统!";
                    }
                    labelOfScrollWords.setText(temp);

                } else {
//					textOfChinese.setText("没有这个单词的英文翻译!");
                }

            }
        }
    }

    //滚动字幕的线程的信息
    private class scrollThread implements Runnable {
        //重写的方法
        @Override
        public void run() {
            timer = new Timer(sleeptime, new ActionListener() {
                int fontSize = 12;
                int delta = 1;

                public void actionPerformed(ActionEvent e) {
                    fontSize += delta;
                    if (fontSize > 24) {
                        delta = -1;
                    } else if (fontSize < 12) {
                        delta = 1;
                    }
                    Font font = new Font("SansSerif", Font.BOLD, fontSize);
                    labelOfScrollWords.setFont(font);
                }
            });

            timer.start();

            while (true) {
                try {
                    Thread.sleep(sleeptime);
                    //Thread.sleep(1000);

                } catch (InterruptedException ex) {
                }
                if (stopScrolling == true) {//如果“stop”,线程终止
                    timer.stop();
                    return;
                }
            }

        }
    }

    private class timerThread implements Runnable {
        public void run() {
            while (!stopTimer) {
                Date date = new Date();
                String str = date.toString().substring(11, 19);
                textOfTimer.setText(str);// 把时间显示在文本框中
                try {
                    Thread.sleep(1000);// 休眠1000毫秒
                } catch (InterruptedException ex) {
                }
            }
        }
    }


}

 

 

相关文章:

  • 【2023.3.18 美团校招】
  • 【华为OD机试 2023最新 】 寻找相似单词(C++ 100%)
  • 新目标大学英语综合教程1-4
  • 指针的用法和注意事项(三)
  • Python(白银时代)——模块、包、异常
  • 网络安全专家最爱用的9大工具
  • 处理机调度典型调度算法
  • HBase客户端、服务器端、列簇设计、HDFS相关优化,HBase写性能优化切入点,写异常问题检查点
  • 技术方案开发——红外测温仪方案
  • Chat GPT介绍
  • 探索Python编程语言:创新技术与应用领域
  • AC笔记 | Leetcode 0394 —— 辅助栈
  • Idea常用快捷键设置
  • 5.springcloud微服务架构搭建 之 《springboot集成Hystrix》
  • 【历史上的今天】2 月 28 日:阿帕网退役;Quintus 收购 Mustang;同步电流磁芯存储器获得专利
  • [case10]使用RSQL实现端到端的动态查询
  • 2019年如何成为全栈工程师?
  • Angularjs之国际化
  • CoolViewPager:即刻刷新,自定义边缘效果颜色,双向自动循环,内置垂直切换效果,想要的都在这里...
  • Effective Java 笔记(一)
  • exports和module.exports
  • JavaScript学习总结——原型
  • java正则表式的使用
  • js ES6 求数组的交集,并集,还有差集
  • js数组之filter
  • Linux快速配置 VIM 实现语法高亮 补全 缩进等功能
  • node-glob通配符
  • October CMS - 快速入门 9 Images And Galleries
  • python_bomb----数据类型总结
  • Python学习之路16-使用API
  • Redis提升并发能力 | 从0开始构建SpringCloud微服务(2)
  • 搞机器学习要哪些技能
  • 解析 Webpack中import、require、按需加载的执行过程
  • 写给高年级小学生看的《Bash 指南》
  • 用jQuery怎么做到前后端分离
  • ​​​​​​​​​​​​​​汽车网络信息安全分析方法论
  • #gStore-weekly | gStore最新版本1.0之三角形计数函数的使用
  • #includecmath
  • (2)STL算法之元素计数
  • (DFS + 剪枝)【洛谷P1731】 [NOI1999] 生日蛋糕
  • (编译到47%失败)to be deleted
  • (超详细)语音信号处理之特征提取
  • (附源码)springboot 智能停车场系统 毕业设计065415
  • (附源码)springboot美食分享系统 毕业设计 612231
  • (附源码)ssm教材管理系统 毕业设计 011229
  • (七)MySQL是如何将LRU链表的使用性能优化到极致的?
  • (转)JAVA中的堆栈
  • .axf 转化 .bin文件 的方法
  • .Net MVC4 上传大文件,并保存表单
  • .net web项目 调用webService
  • .NET 使用 JustAssembly 比较两个不同版本程序集的 API 变化
  • .NET/C# 反射的的性能数据,以及高性能开发建议(反射获取 Attribute 和反射调用方法)
  • .NET/C# 使用反射注册事件
  • .net打印*三角形
  • .NET委托:一个关于C#的睡前故事