使用 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 | 用途 |
|---|---|
JOptionPane.showInputDialog(String) | 顯示模態輸入對話框,返回用戶輸入字串;取消返回 null。 |
Integer.parseInt(String) | 字串轉整數,異常需捕獲(簡化版未捕獲,生產碼需加 try-catch)。 |
System.out.print/println | 控制台輸出(GUI 程式亦可輸出至控制台)。 |
parseInt 捕獲 NumberFormatException,提示「請輸入有效整數」。JTextArea 或 JOptionPane.showMessageDialog 顯示矩陣,而非控制台。SwingUtilities.invokeLater。