Java 练习题

  1. 编写一个 Application 并定义一个异常类,要求完成如下操作。定义一个 money 类,包括:
    存款余额:成员变量 yu;
    存款操作:方法 putMoney(double money)
    取款操作:方法 getMoney(double money)
    获取余额:方法 getYu()
    如果存款余额小于取款额时,显示当前余额,并告之不能取款,否则显示取款成功的信息。
public class Exercise {

    public static void main(String[] args) {
        Money money = new Money();
        money.putMoney(1000);
        try {
            money.getMoney(500);
        } catch (MoneyException e) {
            System.out.println("当前余额为:" + money.getYu() + " 不能取款");
        }
    }
}

class MoneyException extends Exception {
    MoneyException() {
    }
}

class Money {
    private double yu = 0;
    public void putMoney(double money) {
        yu = yu + money;
        System.out.println("存款成功!");
    }
    public void getMoney(double money) throws MoneyException{
        if (!(yu >= money))
            throw new MoneyException();
        yu = yu - money;
        System.out.println("取款成功!");
    }
    public double getYu() {
        return yu;
    }
}
  1. 实现两个定时器,一个线程每隔 1s 显示一次,一个线程每隔 3s 显示一次。
public class Exercise {

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.start();
        thread2.start();
    }
}

class Thread1 extends Thread {
    public void run() {
        while (true) {
            System.out.println("第一个线程!");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Thread2 extends Thread {
    public void run() {
        while (true) {
            System.out.println("第二个线程!");
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 编写一个类,类名为 MulThread,定义含一个字符串参数的构造方法,并实现 Runnable 接口,接口中的 run() 方法如下实现,方法先在命令行显示该线程信息,然后随机休眠小于 1s 的时间,最后显示线程结束信息:finished + 线程名。编写一个 Application 程序,创建 MulThread 类的 3 个线程对象 t1, t2, t3,并再启动这 3 个线程。
public class Exercise {

    public static void main(String[] args) {
        MulThread th1 = new MulThread("th1");
        MulThread th2 = new MulThread("th2");
        MulThread th3 = new MulThread("th3");
        Thread t1 = new Thread(th1);
        Thread t2 = new Thread(th2);
        Thread t3 = new Thread(th3);
        t1.start();
        t2.start();
        t3.start();

    }
}

class MulThread implements Runnable {
    private String string;
    MulThread (String str) {
        string = str;
    }
    public void run() {
        System.out.println(string);
        try {
            Thread.sleep((int)(Math.random() * 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finished " + string);
    }
}
  1. 设计一个窗口,内含一个按钮。开始运行时,按钮显示 “click me !” 字样,但按下按钮时,按钮上面的文字变成 “click me again !”,再按一次,则会变成 “click me !”。如此循环。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Exercise {

    public static void main(String[] args) {
        new Windows();
    }
}

class Windows extends JFrame {
    JButton button;
    public Windows(){
        button = new JButton("Click Me");
        this.add(button);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if(button.getText().equals("Click Me")){
                    button.setText("Click Me Again");
                }
                else button.setText("Click Me");
            }
        });

        this.setVisible(true);
        this.setBounds(50,50,200,150);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
  1. 编写一个应用程序,设计 4 个按钮,分别明明 “加”,“减”,“乘”,“除”;有三个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class Exercise {
    public static void main(String[] args) {
        new Calculaor();
    }
}
class Calculaor implements ActionListener{
    private JButton jb1,jb2,jb3,jb4;
    private JTextField jt1,jt2,jt3;
    private JFrame jf;
    private Box box1,box2,basebox;
    public Calculaor(){
        jf=new JFrame("简单计算器");
        jf.setBounds(300, 300, 440, 130);
        jf.setVisible(true);
        jf.setLayout(new FlowLayout());

        jb1 = new JButton("加");
        jb2 = new JButton("减");
        jb3 = new JButton("乘");
        jb4 = new JButton("除");

        jb1.addActionListener(this);
        jb2.addActionListener(this);
        jb3.addActionListener(this);
        jb4.addActionListener(this);

        jt1 = new JTextField(" ");
        jt2 = new JTextField(" ");
        jt3 = new JTextField(" ");

        Dimension dim = new Dimension(100, 20);
        Dimension dim2 = new Dimension(180, 20);
        jt1.setPreferredSize(dim);
        jt2.setPreferredSize(dim);
        jt3.setPreferredSize(dim2);
        jt3.setEditable(false);
        jt3.setBackground(Color.gray);

        box1 = Box.createHorizontalBox();
        box1.add(jt1);
        box1.add(Box.createHorizontalStrut(10));
        box1.add(jt2);
        box1.add(Box.createHorizontalStrut(10));
        box1.add(jt3);

        box2 = Box.createHorizontalBox();
        box2.add(jb1);
        box2.add(Box.createHorizontalStrut(10));
        box2.add(jb2);
        box2.add(Box.createHorizontalStrut(10));
        box2.add(jb3);
        box2.add(Box.createHorizontalStrut(10));
        box2.add(jb4);

        basebox = Box.createVerticalBox();
        basebox.add(box1);
        basebox.add(Box.createVerticalStrut(10));
        basebox.add(box2);
        jf.add(basebox);
        jf.validate();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e) {
        String temp1 = jt1.getText().trim();
        String temp2 = jt2.getText().trim();
        if(temp1.equals("")||temp2.equals("")){
            JOptionPane.showMessageDialog(jf,"文本框不能为空。");
        }else{
            double a = 0, b = 0;
            try{
                a = Double.parseDouble(temp1);
                b = Double.parseDouble(temp2);
            }catch(Exception e1){
                JOptionPane.showMessageDialog(jf,"您输入了非法字符,请输入正确的数字。");
                return;
            }
            if(e.getSource() == jb1){
                jt3.setText(""+(a + b));
                System.out.println("" + (a + b));
            }else if(e.getSource() == jb2){
                jt3.setText("" + (a - b));
            }else if(e.getSource() == jb3){
                jt3.setText("" + (a * b));
            }else if(e.getSource() == jb4){
                jt3.setText("" + (a / b));
            }
        }
    }
}
  1. 编写一个图形用户界面的应用程序,包括两个文本框和一个按钮,当单击按钮时,可以把一个文本框中的内容复制到另一个文本框中。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Exercise {
    public static void main(String[] args) {
        new Windows();
    }
}

class Windows extends JFrame {
    JButton button = new JButton("Add");
    JTextField textField1 = new JTextField(30);
    JTextField textField2 = new JTextField(30);

    public Windows() {
        Container app = this.getContentPane();
        BoxLayout boxLayout = new BoxLayout(app, BoxLayout.X_AXIS);
        setLayout(boxLayout);
        add(textField1);
        JPanel panel = new JPanel();
        panel.add(button);
        add(panel);
        add(textField2);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (textField1.getText().length() > 0) {
                    textField2.setText(textField2.getText() + textField1.getText() + "\n");
                    textField1.setText("");
                }
            }
        });
        setVisible(true);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
  1. 编写一个应用程序,要求有一个含有菜单的窗口,窗口中有文本区组件。菜单有 “打开文件” 的菜单项,当单击菜单项时,使用输入流将一个名为 “hello.txt” 文件的内容读入到文本区。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.swing.*;

public class Exercise {
    public static void main(String[] args) throws IOException{
        File file = new File("hello.txt");
        FileOutputStream out = new FileOutputStream(file);
        String st = new String("This is a string of characters!");
        byte[] bytes = st.getBytes("UTF-8");
        out.write(bytes);
        out.flush();
        out.close();
        new Window();
    }
}

class Window extends JFrame {

    JTextArea textArea = new JTextArea(20, 30);

    public Window() throws IOException{
        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        JMenuBar menuBar = new JMenuBar();

        JButton openFile = new JButton("Open File");
        menuBar.add(openFile);
        add(menuBar);
        add(textArea);

        openFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                File file = new File("hello.txt");
                FileInputStream in = null;
                try {
                    in = new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                byte[] bytes = new byte[1024];
                try {
                    while (in.read(bytes) != -1) {
                        textArea.setText(new String(bytes));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        setVisible(true);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值