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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章