首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Swing 輸入對話框實現矩陣列印:互動式行列輸入與圖形輸出

     編輯:Java 相關知識

程式功能

使用 JOptionPane.showInputDialog 獲取用戶輸入的行數與列數,驗證合法性後在控制台列印星號矩陣,並提示是否繼續。

完整代碼(重構版)


import javax.swing.*;

public class MatrixPrinter {
    public static void main(String[] args) {
        int continueFlag;
        do {
            // 1. 獲取行數
            String rowStr = JOptionPane.showInputDialog("請輸入圖形的行數:");
            if (rowStr == null) return; // 用戶取消
            int rows = Integer.parseInt(rowStr.trim());

            // 2. 獲取列數
            String colStr = JOptionPane.showInputDialog("請輸入圖形的列數:");
            if (colStr == null) return;
            int cols = Integer.parseInt(colStr.trim());

            // 3. 列印矩陣
            continueFlag = printMatrix(rows, cols);
        } while (continueFlag == 1);
        System.exit(0);
    }

    static int printMatrix(int rows, int cols) {
        // 輸入驗證
        if (rows <= 0 || cols <= 0) {
            System.out.println("輸入的行列數有誤,請重新輸入!");
            return 0;
        }

        // 列印星號矩陣
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        System.out.println("\n這是您想要的圖形:" + rows + "行 × " + cols + "列");

        // 詢問是否繼續
        String again = JOptionPane.showInputDialog("您想再次畫圖嗎? 是(1) 否(2)");
        if (again == null) return 0;
        return Integer.parseInt(again.trim());
    }
}

關鍵 API 與流程

API用途
JOptionPane.showInputDialog(String)顯示模態輸入對話框,返回用戶輸入字串;取消返回 null。
Integer.parseInt(String)字串轉整數,異常需捕獲(簡化版未捕獲,生產碼需加 try-catch)。
System.out.print/println控制台輸出(GUI 程式亦可輸出至控制台)。

改進建議

  • 異常處理:包裹 parseInt 捕獲 NumberFormatException,提示「請輸入有效整數」。
  • 輸入驗證:限制行列數上限(如 100),避免刷屏。
  • GUI 輸出:改用 JTextArea 或 JOptionPane.showMessageDialog 顯示矩陣,而非控制台。
  • 資源釋放:Swing 程式應在 EDT 運行,主方法建議用 SwingUtilities.invokeLater。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved