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

Java 生成隨機數並求和:JOptionPane 對話框交互完整實例

     編輯:Java 相關知識

Java 隨機數生成與 Swing 圖形化交互實戰

本文通過一個完整的「生成 10 個 1000 以內隨機數、顯示數組、計算求和、彈窗展示結果」的案例,講解 Math.random()、數組操作、JOptionPane 對話框使用及基礎 GUI 程序結構。

一、核心代碼實現

1.1 完整可運行程序


package com.example.random;

import javax.swing.JOptionPane;

public class RandomSumDemo {
    
    public static void main(String[] args) {
        // 1. 生成 10 個 0-999 隨機整數
        int[] numbers = new int[10];
        int sum = 0;
        StringBuilder output = new StringBuilder("生成的 10 個隨機數(0-999):\n");
        
        for (int i = 0; i < numbers.length; i++) {
            // Math.random() 返回 [0.0, 1.0) 雙精度浮點數
            // 乘以 1000 得到 [0.0, 1000.0),強轉 int 截取整數部分
            numbers[i] = (int) (Math.random() * 1000);
            sum += numbers[i];
            
            // 格式化輸出
            output.append(String.format("%4d", numbers[i]));
            if ((i + 1) % 5 == 0) output.append("\n"); // 每 5 個換行
            else output.append("  ");
        }
        
        output.append("\n\n數組元素總和:").append(sum);
        
        // 2. 彈出消息對話框顯示結果
        JOptionPane.showMessageDialog(
            null,                    // 父組件 null 表示居中顯示
            output.toString(),       // 消息內容
            "隨機數生成結果",         // 對話框標題
            JOptionPane.PLAIN_MESSAGE // 消息類型:純文本
        );
    }
}

1.2 關鍵 API 解析

API說明常用重載
Math.random()返回 [0.0, 1.0) 偽隨機 double無參數
JOptionPane.showMessageDialog顯示模態信息對話框parent, message, title, messageType
JOptionPane.showInputDialog顯示輸入對話框返回用戶輸入字符串
JOptionPane.showConfirmDialog顯示確認對話框返回 YES/NO/CANCEL_OPTION
JOptionPane.showOptionDialog最通用的對話框自定義按鈕、圖標、選項

二、進階擴展:交互式版本

2.1 用戶自定義參數版


public class InteractiveRandomSum {
    
    public static void main(String[] args) {
        // 1. 獲取用戶輸入:生成個數
        String countStr = JOptionPane.showInputDialog(
            null,
            "請輸入要生成的隨機數個數(1-100):",
            "參數設置",
            JOptionPane.QUESTION_MESSAGE
        );
        
        if (countStr == null) return; // 用戶點擊取消
        
        int count;
        try {
            count = Integer.parseInt(countStr.trim());
            if (count < 1 || count > 100) throw new NumberFormatException();
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "請輸入 1-100 之間的整數!", "輸入錯誤", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 2. 獲取範圍上限
        String maxStr = JOptionPane.showInputDialog(
            null,
            "請輸入隨機數最大值(≥1):",
            "參數設置",
            JOptionPane.QUESTION_MESSAGE
        );
        
        if (maxStr == null) return;
        
        int max;
        try {
            max = Integer.parseInt(maxStr.trim());
            if (max < 1) throw new NumberFormatException();
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "請輸入大於 0 的整數!", "輸入錯誤", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 3. 生成並計算
        int[] numbers = new int[count];
        int sum = 0;
        StringBuilder sb = new StringBuilder();
        sb.append("生成 ").append(count).append(" 個 [0, ").append(max).append(") 隨機數:\n");
        
        for (int i = 0; i < count; i++) {
            numbers[i] = (int) (Math.random() * max);
            sum += numbers[i];
            sb.append(String.format("%5d", numbers[i]));
            if ((i + 1) % 10 == 0) sb.append("\n");
            else sb.append(" ");
        }
        
        sb.append("\n\n統計信息:\n");
        sb.append("總和:").append(sum).append("\n");
        sb.append("平均值:").append(String.format("%.2f", (double) sum / count)).append("\n");
        sb.append("最大值:").append(maxOf(numbers)).append("\n");
        sb.append("最小值:").append(minOf(numbers));
        
        // 4. 顯示結果,提供複製功能
        JOptionPane.showMessageDialog(
            null,
            sb.toString(),
            "統計結果",
            JOptionPane.INFORMATION_MESSAGE
        );
    }
    
    private static int maxOf(int[] arr) {
        int max = arr[0];
        for (int v : arr) if (v > max) max = v;
        return max;
    }
    
    private static int minOf(int[] arr) {
        int min = arr[0];
        for (int v : arr) if (v < min) min = v;
        return min;
    }
}

2.2 圖形化界面版(JFrame)


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

public class RandomSumGUI extends JFrame {
    
    private JTextField tfCount, tfMax;
    private JTextArea taResult;
    private JButton btnGenerate, btnClear;
    
    public RandomSumGUI() {
        setTitle("隨機數生成器");
        setSize(500, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        initComponents();
        layoutComponents();
        addListeners();
    }
    
    private void initComponents() {
        tfCount = new JTextField("10", 5);
        tfMax = new JTextField("1000", 5);
        taResult = new JTextArea();
        taResult.setEditable(false);
        taResult.setFont(new Font("Monospaced", Font.PLAIN, 14));
        btnGenerate = new JButton("生成並求和");
        btnClear = new JButton("清空");
    }
    
    private void layoutComponents() {
        JPanel top = new JPanel(new FlowLayout(FlowLayout.LEFT));
        top.add(new JLabel("個數:"));
        top.add(tfCount);
        top.add(new JLabel("  最大值:"));
        top.add(tfMax);
        top.add(btnGenerate);
        top.add(btnClear);
        
        JScrollPane scroll = new JScrollPane(taResult);
        
        setLayout(new BorderLayout());
        add(top, BorderLayout.NORTH);
        add(scroll, BorderLayout.CENTER);
    }
    
    private void addListeners() {
        btnGenerate.addActionListener(e -> generate());
        btnClear.addActionListener(e -> taResult.setText(""));
    }
    
    private void generate() {
        try {
            int count = Integer.parseInt(tfCount.getText().trim());
            int max = Integer.parseInt(tfMax.getText().trim());
            if (count < 1 || count > 1000 || max < 1) throw new NumberFormatException();
            
            int[] nums = new int[count];
            int sum = 0;
            StringBuilder sb = new StringBuilder();
            
            for (int i = 0; i < count; i++) {
                nums[i] = (int) (Math.random() * max);
                sum += nums[i];
                sb.append(String.format("%5d", nums[i]));
                if ((i + 1) % 15 == 0) sb.append("\n");
                else sb.append(" ");
            }
            
            sb.append("\n\n總和: ").append(sum)
              .append("\n平均: ").append(String.format("%.2f", (double) sum / count))
              .append("\n最大: ").append(maxOf(nums))
              .append("\n最小: ").append(minOf(nums));
            
            taResult.setText(sb.toString());
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "請輸入有效的正整數!", "錯誤", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private static int maxOf(int[] a) { int m = a[0]; for (int v : a) if (v > m) m = v; return m; }
    private static int minOf(int[] a) { int m = a[0]; for (int v : a) if (v < m) m = v; return m; }
    
    public static void main(String[] args) {
        // EDT 線程啟動 GUI
        SwingUtilities.invokeLater(() -> new RandomSumGUI().setVisible(true));
    }
}

三、隨機數生成最佳實踐

3.1 Math.random() 局限性

  • 線程安全但性能一般(內部同步)
  • 只能生成 double,需轉換
  • 無法指定種子,不可復現

3.2 推薦:ThreadLocalRandom (JDK 7+)


import java.util.concurrent.ThreadLocalRandom;

// 線程本地隨機數生成器,高性能、無競爭
int randomInt = ThreadLocalRandom.current().nextInt(1000); // [0, 1000)
int randomIntRange = ThreadLocalRandom.current().nextInt(100, 1000); // [100, 1000)
long randomLong = ThreadLocalRandom.current().nextLong();
double randomDouble = ThreadLocalRandom.current().nextDouble();

3.3 安全場景:SecureRandom


import java.security.SecureRandom;

// 密碼學安全隨機數,用於 Token、Session ID、加密密鑰
SecureRandom secureRandom = new SecureRandom();
byte[] token = new byte[32];
secureRandom.nextBytes(token);
// 或
String sessionId = new BigInteger(130, secureRandom).toString(32);

四、常見問題 FAQ

問題原因解決
對話框不顯示/程序卡死未在 EDT 線程操作 Swing 組件主方法用 SwingUtilities.invokeLater
中文亂碼源文件編碼與編譯器不一致IDE 設置 UTF-8,javac -encoding UTF-8
生成的數重複偽隨機本質,種子相同序列相同使用 SecureRandom 或洗牌算法
大量數字顯示不全對話框大小固定用 JScrollPane 包裹 JTextArea

從簡單的控制台程序到圖形化交互應用,掌握隨機數生成與 Swing 基礎組件的使用,是 Java 客戶端開發的入門必修課。建議嘗試擴展:添加導出文件、圖表展示、歷史記錄等功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved