《面向对象与Java程序设计》(第二版)朱福喜 课后部分代码题

文章目录


《面向对象与Java程序设计》(第二版)朱福喜

第一章代码题

12.创建一个程序,作为命令行加法器,将两个相加的数作为命令行参数传递给main方法,然后输出结果。

public class Add{
	public static void main(String[] args){
		double x = Double.valueOf(args[0]).doubleValue(), //将字符串化为数值
			   y = Double.valueOf(args[1]).doubleValue();
		System.out.println("x+y=" + (x+y));		   
	}
}

用PowerShell的运行结果:
在这里插入图片描述



第二章代码题

5.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每一位都提出来并打印

public class PrintNumber{
	public static void main(String args[]){
		int n = 1678;
		System.out.print(n/1000 + " ");
		System.out.print(n/100%10 + " ");
		System.out.print(n/10%10 + " ");
		System.out.print(n%10 + " ");
	}
}

在这里插入图片描述

12.使用数组存储一个英文句子 “Java is an object oriented programming language”,显示该句子,并算出每个单词的平均字母数

public class AverageNumberLetters{
	public static void main(String args[]){
		String s = "Java is an object oriented programming language";
		String[] t = s.split(" ");
		double sum = 0,num = 0;
		System.out.println(s);
		for(int i = 0; i < t.length; i++){
			sum += t[i].length();
			num ++;
		}
		System.out.println("平均字母数:" + sum/num);
	}
}

在这里插入图片描述

13.用数组计算复利。有$10000,年利率为6.5%,假设每月计息一次,计算10年的复利。输出要包括每年的利息、结余以及到该年为止的平均利息

public class CompoundInterest{
	public static void main(String args[]){
		double rate = 0.065/12; //月利率 
		double principal = 10000,sum = principal,t = 0;
		double[] interest = new double[11]; //每年利息 
		for(int i = 1; i <= 10; i++){
			for(int j = 1; j <= 12; j++){
				sum = sum*(1 + rate);
			} 
			interest[i] = sum - principal;
			System.out.println("第 " + i + " 年的利息:" + interest[i] + "  和结余:" + sum);
			principal = sum;
			for(int k = 1; k <= i; k++){
				t += interest[k]; 
			} 
			System.out.println("到该年为止的平均利息:" + t/i);
			t = 0;
		}	
	
	}
}

在这里插入图片描述

14.定义一个4行4列的double型二维数组,并创建一个方法显示数组,计算任意给定的行、给定的列、主对角线和副对角线的和以及数组中的最大值

public class Array{
	public static void main(String args[]){
		double[][] s = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
		double[] sum1 = new double[4]; //每行 
		double[] sum2 = new double[4]; //每列 
		double sum3 = 0;//主对角线
		double sum4 = 0;//副对角线 
		double max = s[0][0]; 
		for(int i = 0; i < 4; i++){
			sum1[i] = 0;
			sum2[i] = 0;
			for(int j = 0; j < 4; j++){
				sum1[i] += s[i][j]; 
				sum2[i] += s[j][i];
				if(s[i][j] > max)max = s[i][j]; //最大值 
				if(i == j)sum3 += s[i][j];
				if(i+j == 4-1)sum4 += s[i][j]; 
			}
		}
		for(int k = 0; k < 4; k++) 
			System.out.println("第 " + (k+1) + " 行:" + sum1[k]);
		for(int k = 0; k < 4; k++) 
			System.out.println("第 " + (k+1) + " 列:" + sum2[k]);
		System.out.println("主,副对角线的和与最大值分别是:" + "("+ (sum3+sum4)+ "," + max +")");		
	}
}

在这里插入图片描述



第四章代码题

15.假如我们要编写一个地址簿的程序,设计一个能存储姓名、E-mail地址,并能显示一个地址的Address类

public class Address{            
	private String name;
	private String email;
	 
	public void setName(String name){
		this.name = name;
	}
	
	public void setEmail(String email){
		this.email = email;
	}
	
	public String getName(){
		return name;
	}
	
	public String getEmail(){
		return email;
	}
	
	public void display(){
		System.out.println(this.name + "’s Address:" + this.email);
	}
	
} 

18.创建一个包含private、public、protected变量的类。再创建一个包含标准main()方法的类,在类中实例化第一个类的对象,并访问该对象的成员。

//这个题目我就随便设置了几个值对应三种访问控制符,类名也随便起的,无所谓了

class Test{
	Test(){
	}
	Test(String name,int age,String sex){
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	public String getName(){  //返回私有成员变量
		return name;
	}
	private String name;
	public int age;
	protected String sex;
}

public class Test18{
	public static void main(String[] args){
		Test test = new Test("zgh",18,"male");
		//System.out.println(test.name); //name是私有的,这样访问会报错
		System.out.println(test.getName());//私有成员变量的访问要借助于方法
		System.out.println(test.age);
		System.out.println(test.sex);
	}
}

20.使用静态成员变量来计算内存中的实例化的对象数目。

//这个题目借助于构造器就ok了

public class CalculateInstances{
	static int num;
	CalculateInstances(){
		num++;
	}
}

测试上述代码的正确性:

public class CalculateInstances{
	static int num;
	CalculateInstances(){
		num++;
	}
	public static void main(String[] args){
		System.out.println(CalculateInstances.num);
		CalculateInstances a = new CalculateInstances();
		System.out.println(CalculateInstances.num);
		CalculateInstances b = new CalculateInstances();
		System.out.println(CalculateInstances.num);
		CalculateInstances c= new CalculateInstances();
		System.out.println(CalculateInstances.num);
		CalculateInstances d= new CalculateInstances();
		System.out.println(CalculateInstances.num);
	}
}

result:
在这里插入图片描述

21.创建一个Student类,它能存储和显示学生的姓名和GPA,考虑GPA不一定知道,所以提供多钟版本的构造方法来创建Student类的对象。

public class Student{
	private String name;
	private float GPA; 
	public Student(){
	}
	public Student(String name){
		this.name = name;
	}
	public Student(String name,float GPA){
		this.name = name;
		this.GPA = GPA;
	}
}


第五章代码题

13. 以第4章15题中定义的Address类作为超类,定义一个子类,它拥有另外一个成员变量来存储电话号码。

(第4章15题如此:假如我们要编写一个地址簿的程序,设计一个能存储姓名、E-mail地址,并能显示一个地址的Address类)

class Address{
    private String name;
    private String email;

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

    public void setEmail(String email){
        this.email = email;
    }

    public String getName(){
        return name;
    }

    public String getEmail(){
        return email;
    }

    public void display(){
        System.out.println(this.name + "’s Address:" + this.email);
    }

}

public class AddressSon extends Address{
    private String Email;  //另外一个成员变量来存储电话号码

    public void setEmail(String email) {
        Email = email;
    }

    public String getEmail() {
        return Email;
    }
}

19.创建一个称为List的类,它可存储任何类型的对象,并可以在任何时候增加或删除对象。

第一个解: 首先说一下,下面我写的代码已经超出题目要求了(我将设计的List类,增删对象时,可以动态的改变数组的长度)

public class List<E> { //泛型
    //描述事物
    //属性:
    private static final int DEFAULT_CAPACITY = 10;
    private Object[] elementData;//给ArrayBox一个初始数组
    private int size = 0;//记录ArrayBox中有效数据的个数,给一个初始值

    //构造方法:
    public List(){
        elementData = new Object[DEFAULT_CAPACITY];
    }
    public List(int capacity){
        elementData = new Object[capacity];
    }


    //方法:
    //1.需要设计一个方法,用来添加元素
    //      提供什么条件(参数)  返回一个结果(返回值)--告知用户一个结果,是否存储成功 boolean
    //
    //存储元素的时候方法给位置存放
    //如果位置满了,方法要解决这个问题

    //添加元素
    public boolean add(E element){//E是创建box对象时,规定的类型

        //首先要确保自己的属性数组的内部容量够不够用
        //      调用一个方法,来确定内部容量够用否
        this.ensureCapacity(size+1);

        //我想把element存入elementData数组中
        elementData[size++] = element;
        return true;
    }
    //访问控制修饰符是private的,是不希望用户看到的方法
    private void ensureCapacity(int minCapacity){    //来确定内部容量够用否
        //minCapacity即用户所需最小空间
        if(minCapacity > elementData.length){
            //如果内部容量不够用,调用一个扩容的方法
            this.grow(minCapacity);
        }
    }

    private void grow(int minCapacity){  //给内部空间扩容
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity>>1);//即oldCapacty*1.5
        if(newCapacity < minCapacity){
            newCapacity = minCapacity;
        }

        //既然要把空间扩容,要把旧数组的内容放到新的更大空间的数组中
        //调用一个类,复制数组内容
        elementData = this.copyOf(elementData,newCapacity);
    }

    private Object[] copyOf(Object[] oldArray,int newCapacity){  //把就数组的内容复制到新的数组中
        Object[] newArray = new Object[newCapacity];
        for(int i = 0; i < elementData.length; i++){
            newArray[i] = oldArray[i];
        }
        return newArray;
    }



    //2.需要设计一个方法,删除元素
    public E remove(int index){
        //检测index是否合法
        this.rangeCheck(index);

        //将要删除的元素保存下来,返回给用户
        E oldValue = (E)elementData[index];

        //删除元素
        for(int i = index;i < size-1; i++){
            elementData[i] = elementData[i+1];
        }
        elementData[--size] = null;//末尾元素清空

        return oldValue;
    }

    private void rangeCheck(int index){       //检验index是否合法
        if(index < 0 || index > this.size){
            System.out.println("导入索引有问题!!!");
        }
    }

}

第二个解: 这个思路我用到了链表的数据结构

class Node<E> { //定义双向链表的数据结构
    private Node prev;//上一个Node对象
    private E item;  //当前的数据
    private Node next;//下一个Node对象

    public Node(Node prev,E element,Node next){
        this.item = element;
        this.next = next;
        this.prev = prev;
    }

    public E getItem() {
        return item;
    }

    public Node getNext() {
        return next;
    }

    public Node getPrev() {
        return prev;
    }

    public void setItem(E item) {
        this.item = item;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public void setPrev(Node prev) {
        this.prev = prev;
    }
}


public class List<E>{ //泛型
    //先定义头节点和尾节点的属性
    private Node first;
    private Node last;
    private int size = 0;//记录有效元素的个数


    //1.增加元素的方法
    public boolean add(E element) {

        //将element元素存入一个新的node里,挂在链表的尾端
        //      调用linkLast方法
        this.linkLast(element);

        //告知添加成功
        return true;
    }

    private void linkLast(E element){ //将element元素存入一个新的node里,挂在链表的尾端
        //获取链表的尾节点
        Node l = last;

        //创建一个新的Node对象,将新数据包装起来
        Node newNode = new Node(l,element,null);

        //再将新节点设置为尾节点
        last = newNode;

        if(l == null){
            first = newNode;
        }
        else{
            l.setNext(newNode);
        }

        //有效元素增加一个
        size++;

    }


    //2.删除元素的方法
    public void remove(int index) {

        //检测index是否合法
        this.rangeCheck(index);

        //找到index位置的那个Node
        //调用node方法
        Node targetNode = this.node(index);
        
        //删除当前元素的目标节点
        //调用
        this.unLink(targetNode);

        //有效元素减少一个
        size--;

        //返回被删元素
        return oldValue;
    }

    private Node node(int index){  //找寻index对应位置的那个Node对象,将对象中的数据据取出来

        Node targetNode;//用来存储当前目标元素的对象

        if(index < (index>>1)){
            targetNode = first;
            for(int i = 0; i < index; i++){
                targetNode = targetNode.getNext();
            }
        }
        else{
            targetNode = last;
            for(int i = size-1; i > index; i--){
                targetNode = targetNode.getPrev();
            }
        }
        return targetNode;
    }


    private void unLink(Node targetNode){
        if(targetNode.getPrev() == null){
            first = targetNode.getNext();
        }else{
            targetNode.getPrev().setNext(targetNode.getNext());
        }

        if(targetNode.getNext() == null){
            last = targetNode.getNext();
        }else{
            targetNode.getNext().setPrev(targetNode.getPrev());
        }


        targetNode.setNext(null);
        targetNode.setPrev(null);
    }



    private void rangeCheck(int index){       //检验index是否合法
        if(index < 0 || index > this.size){
            System.out.println("导入索引有问题!!!");
        }
    }

}

23.定义一个接口OneToN,在接口体中包含一个抽象方法disp()。定义Sum和Pro类,并分别用不同代码实现OneToN中的disp()方法,在Sum方法中计算1到n的和,在Pro方法中中计算1到n的乘积

public interface  OneToN{
    public int disp();
}
public class Pro implements OneToN{
    private int n;

    public Pro(){}
    public Pro(int n){
        this.n = n;
    }

    public void setN(int n){
        this.n = n;
    }
    public int getN(){
        return this.n;
    }
    
    public int disp(){
        int mul = 1;
        for(int i = 1; i <= n; i++){
            mul *= n;
        }
        return mul;
    }

}
public class Sum implements OneToN{
    private int n;

    public Sum(){}
    public Sum(int n){
        this.n = n;
    }

    public void setN(int n){
        this.n = n;
    }
    public int getN(){
        return this.n;
    }
    
    public int disp(){
        int sum = 0;
        for(int i = 1; i <= n; i++){
            sum += n;
        }
        return sum;
    }

}

24.编写一个类使用上题中的接口类型衍生的类。

public class Demo{
    public static void main(String[] args){
        Sum sum = new Sum(10);
        Pro pro = new Pro(10);
        System.out.println(sum.disp());
        System.out.println(pro.disp());
    }

}




第六章代码题

10.编写程序,包括一个标签、一个文本框和一个按钮,当用户单击按钮时,程序把文本框中的内容复制到标签中

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Demo extends Frame implements ActionListener {

    private TextField input = new TextField();
    private Label output = new Label();
    private Button add = new Button("add");

    private class WindowCloser extends WindowAdapter {
        public void windowClosing(WindowEvent we){
            System.exit(0);
        }
    }

    public Demo(){
        super("10");
        setup();
        add.addActionListener(this);
        addWindowListener(new WindowCloser());
        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae){
        if(ae.getSource() == add){
            output.setText(input.getText());
        }
    }


    private void setup(){
        Panel top = new Panel();
        top.setLayout(new BorderLayout());
        top.add("West",add);
        top.add("Center",input);
        setLayout(new BorderLayout());
        add("North",top);
        add("Center",output);
    }


    public static void main(String[] args){
        Demo demo = new Demo();
    }
}

在这里插入图片描述
在这里插入图片描述

11. 编写一个Applet响应鼠标事件,用户可以通过拖动鼠标在Applet中画出矩形,并在状态条中显示鼠标当前的位置

//<APPLET code = "Demo.class" width = "300" height = "100">
//</APPLET>

import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class Demo extends Applet implements MouseMotionListener{
    private int xstart = -1,
                ystart = -1;
    private int xend,yend;
    private TextField showPosition;

    public void init(){
        showPosition = new TextField(20);
        add(showPosition);
        addMouseMotionListener(this);
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                xstart = e.getX();
                ystart = e.getY();
            }
        });
    }

    public void paint(Graphics g){
        if(xstart != 1 && ystart != 1){
            g.drawRect(xstart,ystart,xend-xstart,yend-ystart);
            showPosition.setText("x:" + xend + ",y:" + yend);
        }
    }

    public void mouseDragged(MouseEvent me){
        xend = me.getX();
        yend = me.getY();
        repaint();
    }

    public void mouseMoved(MouseEvent e) { }

}

在cmd中输入appletviewer Demo.java,运行即可。
(本人的jdk版本,貌似应该或许是把appletviewer给淘汰了,所以呢,没结果)

12. 使用一个Canvas及其上的字符串来显示各选择组件确定的显示效果

这个题目,真他娘的让我屁屁疼,说的啥啊,就不能说的详细点,无语至极。不管了,就瞎几把按照自己的理解写一个了:

搞一个用户界面,要使用Canvas组件,然后在瞎几把搞几个按钮之类的组件上去,点不同的按钮,画布区出现不同的字符串

package canvas;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CanvasTest extends Frame implements ActionListener {
    private Button b1 = new Button("zgh");
    private Button b2 = new Button("666");
    private Button b3 = new Button("cao~~");
    private DrawCanvas dc = new DrawCanvas();

    public CanvasTest(){
        super("12");
        init();
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        setSize(400,400);
        setVisible(true);
    }

    public void init(){
        Panel buttons = new Panel();
        buttons.setLayout(new FlowLayout());
        buttons.add(b1);
        buttons.add(b2);
        buttons.add(b3);
        setLayout(new BorderLayout());
        add("North",buttons);
        add("Center",dc);
    }

    public void actionPerformed(ActionEvent e){
        if(e.getSource() == b1)
            dc.b1();
        else if(e.getSource() == b3)
            dc.b2();
        else
            dc.b3();
        dc.repaint();
    }

    public static void main(String[] args) {
        CanvasTest ct = new CanvasTest();
    }
}

class DrawCanvas extends Canvas{
    private String temp = "我是谁?我在哪?";
    public void paint(Graphics g){
        g.drawString(temp,50,50);
    }
    public void b1(){
        temp = "张国豪";
    }
    public void b2(){
        temp = "张国豪666";
    }
    public void b3(){
        temp = "这个题目真的无语!";
    }
}

执行后:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

13. 设计一个加法计算器,其中要使用按钮、文本域、布局管理者和标签等构件。

package additive_computer;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Computer extends Frame implements ActionListener {
    private Button add = new Button("add");
    private Button clean = new Button("clean");
    private TextField tf = new TextField(30);
    private Label result = new Label();
    private double sum = 0;

    public Computer(){
        super("13");
        setup();
        add.addActionListener(this);
        clean.addActionListener(this);
        setSize(400,100);
        setVisible(true);
    }

    public void setup(){
        Panel buttons = new Panel();
        buttons.setLayout(new FlowLayout());
        buttons.add(clean);
        buttons.add(add);
        buttons.add(tf);
        setLayout(new BorderLayout());
        add("North",buttons);
        add("Center",result);
    }

    public void actionPerformed(ActionEvent e){
        if(e.getSource() == add){
            sum += new Double(tf.getText());
            tf.setText("");
            result.setText("结果:" + sum);
        }else if(e.getSource() == clean){
            sum = 0;
            tf.setText("");
            result.setText("");
        }
    }

    public static void main(String[] args) {
        Computer computer = new Computer();
    }
}

运行后:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

15. 根据本章所介绍的内容编程:设计一个简单的文字编辑器。

package text_editor;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TextEditor extends Frame implements ActionListener {
    private Button copy = new Button("copy");
    private Button paste = new Button("paste");
    private Button cutting = new Button("cutting");
    private TextField ef = new TextField(30);
    private TextField show = new TextField(30);
    private String temp = null;

    public TextEditor(){
        super("15");
        setup();
        copy.addActionListener(this);
        paste.addActionListener(this);
        cutting.addActionListener(this);
        setVisible(true);
        setSize(400,100);
    }

    public void setup(){
        Panel buttons = new Panel();
        buttons.setLayout(new FlowLayout());
        buttons.add(copy);
        buttons.add(paste);
        buttons.add(cutting);
        setLayout(new BorderLayout());
        add("North",buttons);
        add("Center",ef);
        add("South",show);
    }

    public void actionPerformed(ActionEvent event){
        if(event.getSource() == copy){
            temp = ef.getText();
        }else if(event.getSource() == paste){
            show.setText(temp);
        }else if(event.getSource() == cutting){
            temp = ef.getText();
            ef.setText("");
            show.setText(temp);
        }
    }

    public static void main(String[] args) {
        TextEditor te = new TextEditor();
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述



第七章代码题

11.编写一个程序,使用一个数据输出流来写两个整数到一个文件中去。然后打开这个文件,尝试以浮点值的方式来读取这个数据,是否可以正常工作?

package io;

import java.io.*;

public class Homework11 {
    public static void main(String[] args) {
        File file = new File("E://test.txt");
        FileOutputStream fos = null;
        DataOutputStream dos = null;
        try {
            fos = new FileOutputStream(file,true);
            dos = new DataOutputStream(fos);
            dos.writeInt(6);
            dos.writeInt(8);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        FileInputStream fis = null;
        DataInputStream dis = null;
        try {
            fis = new FileInputStream(file);
            dis = new DataInputStream(fis);
            double value1 = dis.readDouble();
            double value2 = dis.readDouble();
            System.out.println(value1 + "  " + value2);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

写进去没问题,但是读出来会抛出异常java.io.EOFException
因为int是4个字节,double是8个字节
写两个int
以double来读取时,一次就把两个int读完了,再读一次double,没东西可读,所以抛出异常

12.编写一个类似Windows记事本的简单程序,该程序能够创建新文件、读取已经存在的文件、查看和修改文本以及保存为文本文件。

这个题目初看,感觉有那么点叫我们写GUI的意思,但是Java的GUI就是一坨不可描述之物,用起来麻烦的要死,而且早就被市场淘汰的技术,真心不想再写了GUI了,我就只把功能实现即可

package io;

import java.io.*;

public class Homework12 {
    //创建一个新文件
    private void createFile(String path){
        File file = new File(path);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取已经存在的文件
    private void readFile(File file){
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);
            String value = br.readLine();
            while(value != null){
                System.out.println(value);
                value = br.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fr != null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //修改文本,就是写进去新的内容,把原来的文本覆盖掉
    public void modifiy(File file){
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write("我真帅");
            bw.newLine();
            bw.write("德玛西亚,亚索万岁");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    
    public static void main(String[] args) {
        Homework12 h12 = new Homework12();
        h12.createFile("E://test.txt");
        h12.modifiy(new File("E://test.txt"));
        h12.readFile(new File("E://test.txt"));
    }

}

控制台的输出
在这里插入图片描述
文件:
在这里插入图片描述

15.编写一个程序,求2~200之间的素数,并将结果保存在prime.dat文件中。

package io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Homework15 {
    public static void main(String[] args) {
        File file = new File("E://prime.dat");
        FileWriter fw = null;

        try{
            fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            for(int i = 2; i <= 200; i++){
                boolean isFlag = true;//true素数
                for(int j = 2; j <= Math.sqrt(i); j++){
                    if(i % j == 0){
                        isFlag = false;
                        break;
                    }
                }
                if(isFlag){
                    bw.write("" + i); //拼接成串,为了在文件中不乱码
                    bw.flush();
                    bw.newLine();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(fw != null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行后:
在这里插入图片描述
在这里插入图片描述



第八章代码题

5.试用线程的方法编写一个读写文件的应用程序,允许多个读者同时读文件,仅允许一个读者写文件。

随便给文件写点什么进去就行了
在这里插入图片描述
读文件的线程:
在这里插入图片描述
写文件的线程(加一个安全锁):
在这里插入图片描述
测试:
在这里插入图片描述
其中一次运行结果:
在这里插入图片描述

7.模拟一个电子时钟,它可以在任何时候被启动或者停止,并可独立地运行。这个类称为Clock类,他继承Label类。这个类有一个Thread类型的clocker域,以及start()、stop()、run()方法。在run()方法的while循环中,每隔一秒就把系统时间显示为label文本。构造方法初始化时,把label设为系统的当前时间。

package eight;

import java.awt.*;
import java.util.Date;

public class Clock extends Label implements Runnable{
    public Thread clocker = null;
    public Clock(){
        setText(new Date().toString());
    }

    public void start(){
        if(clocker == null){
            clocker = new Thread(this);
            clocker.start();
        }
    }

    @Override
    public void run() {
        Thread currentThread = Thread.currentThread();
        if(clocker == currentThread){
            setText(new Date().toString());
            try{
                clocker.sleep(1000);
            }catch(InterruptedException ie){
                ie.getStackTrace();
            }
        }
    }

    public void stop(){
        clocker = null;
    }

    public static void main(String[] args) {
        Clock c = new Clock();
        c.start();
    }
}

8.创建一个可重用的Ticker Tape类,它可以从右到左缓慢移动显示的文本。

逐帧移动呦(下面这个代码纯属搞笑,莫要当真)

package eight;

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

public class TickerTape extends JFrame{

    private JPanel panel = null;
    private JLabel label = null;
    private int X;

    public  TickerTape(int X){
        super("八.8");
        this.X = X;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
        setBounds(400,280,560,340);
        panel = new JPanel();
        add(panel);
        panel.setLayout(null);
        label = new JLabel("zgh666");
        panel.add(label);
        label.setBounds(X,160,60,40);
        label.setFont(new Font("黑体",Font.BOLD,34));
    }

    public static void main(String s[]) {
        Clock c = new Clock();
        int X = 400;
        new TickerTape(X);
        while(true){
            new TickerTape(X);
            X-=20;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

19.创建一个double stringToDouble(String number)方法,试图把输入的字符串转换成double型的数值,在可能会出现问题时抛出一个异常。采用适当的捕获机制来捕获异常。

在这里插入图片描述
输入数字:
在这里插入图片描述
输入非数字:
在这里插入图片描述



第十章代码题

3.编写一个Applet,获得并显示本机的主机名和IP地址。

做尼玛的applet,拒绝做这玩意
随便把逻辑写一下:
在这里插入图片描述
运行后:
在这里插入图片描述

9.写出一个客户同时有多个服务器为它提供服务的基本框架。

服务器:
在这里插入图片描述
服务器多线程:
在这里插入图片描述
客户端:
在这里插入图片描述


开始测试:

首先运行服务端:
在这里插入图片描述
然后运行客户端:
在这里插入图片描述
再看服务端:
在这里插入图片描述
然后在客户端输入数据:

在这里插入图片描述
再看服务端:
在这里插入图片描述
然后暂停:
客户端:
在这里插入图片描述
服务端:
在这里插入图片描述



如果对你有帮助,请来一个手有赞香



发布了150 篇原创文章 · 获赞 267 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/Zhangguohao666/article/details/101034476
今日推荐