Java語言程序設計課程實驗題目 第四次實驗

1. 在IDE中輸入以下代碼,觀察運行結果,並說明該段程序的作用。

import java.awt.event.*;

import javax.swing.*;

 

public class ButtonExample extends JPanel {

         static JFrame myFrame;

       JLabel label;    

         public ButtonExample(){

             label = new JLabel ("Hello World!");

             JButton hello = new JButton("Hello");         

             // set shortcut key

             hello.setMnemonic('h');

             //Set the ToolTip for the hello button

             hello.setToolTipText("Press Alt+H to test shortcut key");

             hello.addActionListener(new ActionListener(){

                    public void actionPerformed(ActionEvent ae){

                             System.out.println("Hello World!");

                             label.setText("Hello World!");

                    }

           });

             JButton bye = new JButton("Bye");

             bye.setMnemonic('b');

             //Set the ToolTip for the bye button

            bye.setToolTipText("Press Alt+B to test shortcut key");

             bye.addActionListener(new ActionListener(){

                    public void actionPerformed(ActionEvent ae){

                             System.out.println("Bye World!");

                             label.setText("Good Bye World!");

                    }

           });

             add(bye);

             add(hello);

             add(label);

       }

       public static void main(String args[]){

             myFrame = new JFrame("Button Example");

             ButtonExample jt = new ButtonExample();

             myFrame.getContentPane().add("Center",jt);

             myFrame.setSize(300,70);

         myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

             myFrame.setVisible(true);

       }

}

 

2. 編寫程序。

(1)按需求實現以下兩個方法。

//當調用reverse(2016),方法返回6102

public int reverse (int number){}

 

//判斷輸入的參數是否爲迴文數

public Boolean isPalindrome(int number)

 

(2)使用reverse方法實現isPalindrome。

編寫程序,採用JOptionPane的對話框方式,要求用戶輸入一個數字,並採用對話框方式向用戶呈現結論。

注:如果一個數字的反向倒置數字和他的順向數字一樣,則稱其爲迴文數。

 

3. 編寫一個程序用以將AM/PM格式的時間轉換爲24小時格式,例如:

輸入: 9:30pm / 輸出: 21:30

輸入: 9:30am / 輸出: 9:30

輸入: 12:30pm / 輸出: 12:30

輸入: 9:30 / 輸出: 9:30

輸入: 19:30 / 輸出: 19:30

public classTimeConverter {

public static voidmain(String[] args) {

TimeConverter cont = newTimeConverter();

// Test

System.out.println("9:30pm -> "+ cont.convert("9:30pm"));

System.out.println("9:30am -> "+ cont.convert("9:30am"));

System.out.println("12:30pm -> "+ cont.convert("12:30pm"));

System.out.println("9:30 -> "+ cont.convert("9:30"));

System.out.println("19:30 -> "+ cont.convert("19:30"));

}

publicString convert(String ampm) {

  //在此處寫出解決問題的程序代碼 …

}

}

 

4.通過合適的方式(控制檯、可視化控件)分別輸入兩個整型二維數組,對應構成兩個矩陣。編寫程序,實現:

(1) 判斷矩陣輸入是否完成;

(2) 根據兩個輸入矩陣的尺寸,判斷是否能夠進行矩陣乘法運算;

(3) 如兩個輸入矩陣符合矩陣乘法的運算要求,則進行矩陣乘法運算,並通過可視化控件輸出結果。

 

1、

package org.cust.test4;

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

public class ButtonExample extends JPanel {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    static JFrame myFrame;
      JLabel label;    
    public ButtonExample(){
        label = new JLabel ("Hello World!");
        JButton hello = new JButton("Hello");       
        // set shortcut key
        hello.setMnemonic('h');
        //Set the ToolTip for the hello button
        hello.setToolTipText("Press Alt+H to test shortcut key");
        hello.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent ae){
                  System.out.println("Hello World!");
                  label.setText("Hello World!");
              }
          });
        JButton bye = new JButton("Bye");
        bye.setMnemonic('b');
        //Set the ToolTip for the bye button
        bye.setToolTipText("Press Alt+B to test shortcut key");
        bye.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent ae){
                  System.out.println("Bye World!");
                  label.setText("Good Bye World!");
              }
          });
        add(bye);
        add(hello);
        add(label);
      }
      public static void main(String args[]){
        myFrame = new JFrame("Button Example");
        ButtonExample jt = new ButtonExample();
        myFrame.getContentPane().add("Center",jt);
        myFrame.setSize(300,70);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setVisible(true);
      }
      //是一個使用swing包中類實現的窗口ui界面
}
 

2、

package org.cust.test4;

import javax.swing.JOptionPane;

public class Test_1 {

    public static void main(String[] args) {
        boolean flag = true;
        String result = null;
        long number = 0;
        while (flag) {
            String sNumber = JOptionPane.showInputDialog(null, "請輸入一個數字", "迴文數的判斷", JOptionPane.PLAIN_MESSAGE);
            try {
                number = Long.parseLong(sNumber);
                flag = false;
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "輸入有誤,請輸入數字", "迴文數的判斷", JOptionPane.PLAIN_MESSAGE);
                continue;
            }

        }

        Test_1 t = new Test_1();
        if (t.isPalindrome(number)) {
            result = "這個數字是迴文數";
        } else {
            result = "這個數字不是迴文數";
        }
        System.out.println("\n" + result);
        JOptionPane.showMessageDialog(null, result, "結論", JOptionPane.INFORMATION_MESSAGE);

    }

    public long reverse(long number) {
        long reNumber = 0;
        String s1 = number + "";
        StringBuffer sbf = new StringBuffer(s1);
        sbf = sbf.reverse();
        String s2 = new String(sbf);
        reNumber = Long.parseLong(s2);
        return reNumber;
    }

    public Boolean isPalindrome(long number) {
        boolean b = false;
        Test_1 it = new Test_1();
        System.out.println("輸入的數字爲:" + number);
        long reNumber = it.reverse(number);
        System.out.println("反轉後的數字爲:" +reNumber);
        if (number == reNumber) {
            b = true;
        }
        return b;
    }

}
 

3、

package org.cust.test4;

public class TimeConverter {
    public static void main(String[] args) {
        TimeConverter cont = new TimeConverter();
        // Test
        System.out.println("9:30pm -> " + cont.convert("9:30pm"));
        System.out.println("9:30am -> " + cont.convert("9:30am"));
        System.out.println("12:30pm -> " + cont.convert("12:30pm"));
        System.out.println("9:30 -> " + cont.convert("9:30"));
        System.out.println("19:30 -> " + cont.convert("19:30"));
    }

    public String convert(String ampm) {
        // 在此處寫出解決問題的程序代碼 …
        String time = null;
        String prefix = ampm.substring(0, ampm.length() - 2);
        String parts[] = prefix.split(":");
        int hour = Integer.parseInt(parts[0]);
        String suffix = ampm.substring(ampm.length() - 2, ampm.length());
        if (suffix.equals("am")) {
            time = prefix;
        } else if (suffix.equals("pm")) {
            if (hour >= 12) {
                time = prefix;
            } else {
                hour += 12;
                time = hour + ":" + parts[1];
            }
        } else {
            time = ampm;
        }

        return time;
    }
}
 

4、

package org.cust.test4;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.InputMismatchException;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Test_2 extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;

    JButton jb1, jb2, jb3, jb4;
    JPanel jp1, jp2, jp3;
    JLabel jlb1;

    static int a[][], b[][], c[][];

    public Test_2() {

        jb1 = new JButton("矩陣輸入");
        jb2 = new JButton("相乘判斷");
        jb3 = new JButton("矩陣相乘");
        jb4 = new JButton("退出窗口");

        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();

        jlb1 = new JLabel("Test4_4");

        jb1.setFont(new java.awt.Font("楷書", 1, 30));
        jb2.setFont(new java.awt.Font("楷書", 1, 30));
        jb3.setFont(new java.awt.Font("楷書", 1, 30));
        jb4.setFont(new java.awt.Font("楷書", 1, 30));

        jlb1.setFont(new java.awt.Font("楷書", 1, 43));

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

        jp1.add(jlb1);
        jp2.add(jb1);
        jp2.add(jb2);
        jp3.add(jb3);
        jp3.add(jb4);

        this.add(jp1);
        this.add(jp2);
        this.add(jp3);

        this.setLayout(new GridLayout(3, 1));

        this.setSize(800, 500);

        this.setTitle("矩陣相關");

        this.setLocationRelativeTo(null);

        this.setResizable(true);

        this.setVisible(true);

    }

    public static void main(String[] args) {
        Test_2 t1 = new Test_2();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

        if (e.getActionCommand() == "退出窗口") {
            System.exit(0);
        } else if (e.getActionCommand() == "矩陣輸入") {
            JOptionPane.showMessageDialog(null, "\n請在控制檯按照提示依次輸入", "矩陣輸入提示", JOptionPane.WARNING_MESSAGE);
            inputArray();
        } else if (e.getActionCommand() == "相乘判斷") {
            if (Test_2.a == null || Test_2.b == null) {
                JOptionPane.showMessageDialog(null, "請先輸入矩陣", "相乘判斷提示", JOptionPane.ERROR_MESSAGE);
                System.out.println("請先輸入矩陣");
            } else {
                int c[][] = multiplication(Test_2.a, Test_2.b);
                if (c == null) {
                    JOptionPane.showMessageDialog(null, "不符合矩陣相乘條件", "相乘判斷提示", JOptionPane.ERROR_MESSAGE);
                    System.out.println("\n不符合矩陣相乘條件");
                } else {
                    JOptionPane.showMessageDialog(null, "符合矩陣相乘條件", "相乘判斷提示", JOptionPane.WARNING_MESSAGE);
                    System.out.println("\n符合矩陣相乘條件");

                }
            }
        } else if (e.getActionCommand() == "矩陣相乘") {
            if (Test_2.a == null || Test_2.b == null) {
                JOptionPane.showMessageDialog(null, "請先輸入矩陣", "相乘判斷提示", JOptionPane.ERROR_MESSAGE);
                System.out.println("請先輸入矩陣");
            } else {
                int c[][] = multiplication(Test_2.a, Test_2.b);
                if (c == null) {
                    JOptionPane.showMessageDialog(null, "不符合矩陣相乘條件", "相乘判斷提示", JOptionPane.ERROR_MESSAGE);
                    System.out.println("不符合矩陣相乘條件");
                } else {
                    // JOptionPane.showMessageDialog(null, "符合矩陣相乘條件", "相乘判斷提示",
                    // JOptionPane.WARNING_MESSAGE);
                    // System.out.println("\n符合矩陣相乘條件");
                    JOptionPane.showMessageDialog(null, "矩陣相乘結果輸出於控制檯", "相乘結果提示", JOptionPane.WARNING_MESSAGE);
                    showResult(Test_2.c);
                }
            }
        }
    }

    public static void inputArray() {

        boolean flag = true;
        boolean flag_1 = true, flag_2 = true;
        int x1, x2, y1, y2;
        while (flag) {
            Scanner in = new Scanner(System.in);

            System.out.println("請輸入第一個矩陣的行數和列數:");
            try {
                x1 = in.nextInt();
                y1 = in.nextInt();
                if (x1 == 0 || y1 == 0) {
                    System.out.println("矩陣的行數或列數都不能爲0,請重新輸入");
                    continue;
                }
            } catch (InputMismatchException e) {
                // TODO Auto-generated catch block
                System.out.println("輸入有誤請輸入整型數字");
                continue;
            }
            System.out.println("請輸入第二個矩陣的行數和列數:");
            try {
                x2 = in.nextInt();
                y2 = in.nextInt();
                if (x2 == 0 || y2 == 0) {
                    System.out.println("矩陣的行數或列數都不能爲0,請重新輸入");
                    continue;
                }
            } catch (InputMismatchException e) {
                // TODO Auto-generated catch block
                System.out.println("輸入有誤請輸入整型數字");
                continue;
            }
            int c[][] = new int[x1][y1];
            int d[][] = new int[x2][y2];

            System.out.println("第一個矩陣輸入");
            for (int i = 0; i < c.length; i++) {

                System.out.println("請輸入第" + (i + 1) + "行的" + c[0].length + "個數:");

                for (int j = 0; j < c[0].length; j++) {
                    flag_1 = true;
                    while (flag_1) {
                        try {
                            c[i][j] = in.nextInt();

                        } catch (InputMismatchException e) {
                            // TODO Auto-generated catch block
                            System.out.println("輸入有誤請輸入整型數字");
                            in = new Scanner(System.in);
                            continue;

                        }
                        flag_1 = false;
                    }

                }
            }
            System.out.println("第二個矩陣輸入");
            for (int i = 0; i < d.length; i++) {

                System.out.println("請輸入第" + (i + 1) + "行的" + d[0].length + "個數:");

                for (int j = 0; j < d[0].length; j++) {
                    flag_2 = true;
                    while (flag_2) {
                        try {
                            d[i][j] = in.nextInt();

                        } catch (InputMismatchException e) {
                            // TODO Auto-generated catch block
                            System.out.println("輸入有誤請輸入整型數字");
                            in = new Scanner(System.in);
                            continue;

                        }
                        flag_2 = false;
                    }

                }
            }
            Test_2.a = c;
            Test_2.b = d;
            flag = false;

        }
        System.out.println("輸入完成,\n請返回窗口進行其他操作");
        JOptionPane.showMessageDialog(null, "輸入完成", "矩陣輸入提示", JOptionPane.WARNING_MESSAGE);

    }

    public static int[][] multiplication(int a[][], int b[][]) {
        int c[][] = new int[a.length][b[0].length];
        if (a[0].length == b.length) {
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < b[0].length; j++) {
                    for (int k = 0; k < b.length; k++) {
                        c[i][j] += a[i][k] * b[k][j];
                    }
                }
            }
        } else {
            c = null;
        }
        Test_2.c = c;
        return c;
    }

    public static void showResult(int c[][]) {
        int result[][] = c;
        for (int i = 0; i < result.length; i++) {
            System.out.println("");
            for (int j = 0; j < result[i].length; j++) {
                System.out.print("\t" + result[i][j]);
            }
        }
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章