Java课程实验(中)

实验六

(1):

已知有C://test.txt文件。要求从该文件中读取并打印该文件内容到控制台(test.txt文件内容自己书写,文件读入请自学下一章完成)。

要求:对文件读写使用try-catch进行异常捕捉

首先创建一个test.txt文件

(2):

要求:从键盘输入任意网站地址,比如:http://www.baidu.com.cn/index.jsp,使用正则表达式,解析该网址中含有多少个单词。并输出单词及数量

这里将代码中的路径换成你自己的路径

package java实验6;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class First {
    public static void main(String[] args) {
        String filePath = "D:\\eclipse\\workspace\\java实验\\src\\java实验6\\test.txt";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("文件读取发生异常:" + e.getMessage());
        }
    }
}
package java实验6;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Second {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入网站地址:");
        String url = scanner.nextLine();
        scanner.close();
        // 使用正则表达式提取单词
        String regex = "\\b\\w+\\b";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(url);

        int wordCount = 0;
        System.out.println("单词列表:");
        while (matcher.find()) {
            String word = matcher.group();
            System.out.println(word);
            wordCount++;
        }
        System.out.println("单词数量:" + wordCount);
    }
}

实验七

(1):

金额转换(利用StringBuffer及正则表达式)

输入阿拉伯数字金额,比如:1105.05,转换为“壹仟壹佰零伍元零伍分”,并输出。

(2):

要求:

利用泛型,封装一个队列Queue泛型类,实现进队InQueue,出队OutQueue,判断空IsEmpty等函数,并利用test测试进行测试

Class  Queue <T>{

      int real,front;

      ArrayList<T> list;  

}

package java实验7;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class First {
    private static final String[] CHINESE_NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] CHINESE_UNITS = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿"};
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入阿拉伯数字金额:");
        String amount = scanner.nextLine();
        scanner.close();
        // 使用正则表达式将金额拆分为整数部分和小数部分
        String regex = "(\\d+)(\\.\\d+)?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(amount);
        if (matcher.matches()) {
            String integerPart = matcher.group(1);
            String decimalPart = matcher.group(2);
            StringBuffer chineseAmount = new StringBuffer();
            // 转换整数部分
            for (int i = 0; i < integerPart.length(); i++) {
                int digit = Character.getNumericValue(integerPart.charAt(i));
                chineseAmount.append(CHINESE_NUMBERS[digit]);
                chineseAmount.append(CHINESE_UNITS[integerPart.length() - i - 1]);
            }
            // 处理特殊情况
            chineseAmount = new StringBuffer(chineseAmount.toString().replaceAll("零+", "零"));
            chineseAmount = new StringBuffer(chineseAmount.toString().replaceAll("零$", ""));
            chineseAmount = new StringBuffer(chineseAmount.toString().replaceAll("零万", "万"));
            chineseAmount = new StringBuffer(chineseAmount.toString().replaceAll("零亿", "亿"));
            chineseAmount.append("元");
            // 转换小数部分
            if (decimalPart != null) {
                int jiao = Character.getNumericValue(decimalPart.charAt(1));
                int fen = Character.getNumericValue(decimalPart.charAt(2));

                if (jiao != 0) {
                    chineseAmount.append(CHINESE_NUMBERS[jiao]).append("角");
                }
                if (fen != 0) {
                    chineseAmount.append(CHINESE_NUMBERS[fen]).append("分");
                }
            } else {
                chineseAmount.append("整");
            }
            System.out.println("转换结果:" + chineseAmount.toString());
        } else {
            System.out.println("金额格式不正确!");
        }
    }
}

package java实验7;
import java.util.ArrayList;
class Queue<T> {
    private int front;
    private int rear;
    private ArrayList<T> list;
    public Queue() {
        front = 0;
        rear = -1;
        list = new ArrayList<>();
    }
    public void inQueue(T item) {
        rear++;
        list.add(item);
    }
    public T outQueue() {
        if (isEmpty()) {
            throw new IllegalStateException("队列为空");
        }
        T item = list.get(front);
        front++;
        if (front > rear) {
            front = 0;
            rear = -1;
        }
        return item;
    }
    public boolean isEmpty() {
        return rear < front;
    }
    public int size() {
        return rear - front + 1;
    }
}
public class Second {
    public static void main(String[] args) {
        Queue<Integer> queue = new Queue<>();
        // 测试入队
        queue.inQueue(1);
        queue.inQueue(2);
        queue.inQueue(3);
        System.out.println("队列大小:" + queue.size()); // 输出:队列大小:3
        // 测试出队
        System.out.println("出队元素:" + queue.outQueue()); // 输出:出队元素:1
        System.out.println("出队元素:" + queue.outQueue()); // 输出:出队元素:2
        System.out.println("队列大小:" + queue.size()); // 输出:队列大小:1
        // 测试判断空
        System.out.println("队列是否为空:" + queue.isEmpty()); // 输出:队列是否为空:false
        // 测试出队直到队列为空
        System.out.println("出队元素:" + queue.outQueue()); // 输出:出队元素:3
        System.out.println("队列是否为空:" + queue.isEmpty()); // 输出:队列是否为空:true
        // 测试在队列为空时出队
        try {
            queue.outQueue();
        } catch (IllegalStateException e) {
            System.out.println("出队失败:" + e.getMessage()); // 输出:出队失败:队列为空
        }
    }
}

实验八

1、题要求:

龟兔赛跑,看谁先跑到终点(使用多线程技术)

(1)整个赛道长1000米

(2)乌龟先作弊,先跑了400米,兔子才开始跑

(3)乌龟每个单位时间跑1米,兔子每个单位时间跑5米,假定单位时间为1000ms,

(4)输出整个赛道的比赛情况(乌龟、兔子分别处于赛道的什么位置)。

(5)到达终点后线程死亡。

2、

已知有ABCD四个线程,有变量i,其中线程AB对i进行加1,线程CD对i进行减1,四个线程顺序执行,每个线程每次只执行一次。i的初始值为0,打印结果0121012101……

package java实验8;
public class First {
    private static final int TRACK_LENGTH = 1000; // 赛道长度
    private static final int TURTLE_START = 400; // 乌龟起始位置
    private static final int UNIT_TIME = 1000; // 单位时间(毫秒)
    public static void main(String[] args) {
        Thread turtleThread = new Thread(new Animal("乌龟", TURTLE_START, 1));
        Thread rabbitThread = new Thread(new Animal("兔子", 0, 5));
        turtleThread.start();
        rabbitThread.start();
    }
    static class Animal implements Runnable {
        private String name;
        private int position;
        private int speed;
        public Animal(String name, int position, int speed) {
            this.name = name;
            this.position = position;
            this.speed = speed;
        }
        @Override
        public void run() {
            while (position < TRACK_LENGTH) {
                position += speed;
                System.out.println(name + "当前位置:" + position);
                try {
                    Thread.sleep(UNIT_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(name + "到达终点!");
        }
    }
}

package java实验8;
public class Second {
    private static int i = 0;
    private static Object lock = new Object();
    public static void main(String[] args) {
        Thread threadA = new Thread(new ThreadA());
        Thread threadB = new Thread(new ThreadB());
        Thread threadC = new Thread(new ThreadC());
        Thread threadD = new Thread(new ThreadD());
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
    }
    static class ThreadA implements Runnable {
        public void run() {
            while (true) {
                synchronized (lock) {
                    System.out.print(i);
                    i++;
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    static class ThreadB implements Runnable {
        public void run() {
            while (true) {
                synchronized (lock) {
                    System.out.print(i);
                    i++;
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    static class ThreadC implements Runnable {
        public void run() {
            while (true) {
                synchronized (lock) {
                    i--;
                    System.out.print(i);
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    static class ThreadD implements Runnable {
        public void run() {
            while (true) {
                synchronized (lock) {
                    i--;
                    System.out.print(i);
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

实验九

1):

   假定有一面包房,考虑面包制作人员和销售人员的工作过程,面包制作人员将做好的面包放在冰箱里面,销售人员则从冰箱中取出销售,利用多线程机制让他们协同工作:

(1)要求冰箱中有面包时,才能销售,冰箱中没有面包则销售人员必须等待,销售一个面包需要0秒钟,每次销售的面包数量为一个0-10之间的随机数。

(2)当冰箱为有空时,生产人员才能生产,如果冰箱位满时,则不能进行生产,假定生产一个面包的时间为1秒钟;

(3)顾客的到达时间为随机,为0-30秒之间的一个随机数;

(4)冰箱的容量假定为20。

(5)请设计生产人员worker类,销售人员salser类,冰箱Fridge类以及一个test测试类,模拟生产和消费过程

package java实验9;
import java.util.Random;
class Fridge {
    private int capacity;
    private int breadCount;
    public Fridge(int capacity) {
        this.capacity = capacity;
        this.breadCount = 0;
    }
    public synchronized void produceBread() throws InterruptedException {
        while (breadCount >= capacity) {
            wait();
        }
        breadCount++;
        System.out.println("生产了一个面包,当前冰箱中有 " + breadCount + " 个面包");
        notifyAll();
    }
    public synchronized void sellBread(int count) throws InterruptedException {
        while (breadCount < count) {
            wait();
        }
        breadCount -= count;
        System.out.println("销售了 " + count + " 个面包,当前冰箱中有 " + breadCount + " 个面包");
        notifyAll();
    }
}
class Worker implements Runnable {
    private Fridge fridge;
    public Worker(Fridge fridge) {
        this.fridge = fridge;
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                fridge.produceBread();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Salser implements Runnable {
    private Fridge fridge;
    private Random random;

    public Salser(Fridge fridge) {
        this.fridge = fridge;
        this.random = new Random();
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(random.nextInt(30000));
                int count = random.nextInt(10) + 1;
                fridge.sellBread(count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class First {
    public static void main(String[] args) {
        Fridge fridge = new Fridge(20);
        Worker worker = new Worker(fridge);
        Salser salser = new Salser(fridge);
        new Thread(worker).start();
        new Thread(salser).start();
    }
}

点个赞,继续更新😁

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值