Set<String>和JTextField

呓语-MSHK發表於2024-10-03

import javax.swing.;
import java.awt.
;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class Sizeyunsuan {
public static void main(String[] args) {
int i = 1;
Set generatedQuestions = new HashSet<>(); // 用於儲存已生成的題目
int[] answers = new int[30]; // 用於儲存每道題的答案

    String[] questionArray = new String[30]; // 用於儲存每道題
    JTextField[] answerFields = new JTextField[30]; // 用於儲存每道題的答案框

    while (i <= 30) {
        int num1 = (int) (Math.random() * 100);
        int num2 = (int) (Math.random() * 100);
        String question = ""; // 儲存生成的題目
        int answer = 0; // 儲存答案

        if (i <= 5) {
            question = num1 + " + " + num2 + " = ?"; // 加法
            answer = num1 + num2;
        } else if (i <= 10) {
            // 確保 num1 大於 num2
            if (num1 < num2) {
                int temp = num1;
                num1 = num2;
                num2 = temp;
            }
            question = num1 + " - " + num2 + " = ?"; // 減法
            answer = num1 - num2;
        } else if (i <= 20) {
            if (num1 * num2 < 1000) {
                question = num1 + " * " + num2 + " = ?"; // 乘法
                answer = num1 * num2;
            }
        } else if (i <= 30 && num2 * num1 != 0 && num1 != num2) {
            if (num1 % num2 == 0) {
                question = num1 + " / " + num2 + " = ?"; // 除法
                answer = num1 / num2;
            }
        }

        // 檢查題目是否重複
        if (!question.isEmpty() && !generatedQuestions.contains(question)) {
            generatedQuestions.add(question); // 新增題目到集合中
            answers[i - 1] = answer; // 儲存答案
            questionArray[i - 1] = question; // 儲存題目
            answerFields[i - 1] = new JTextField(10); // 建立答案輸入框
            i++; // 僅在成功新增新題目時才增加計數器
        }
    }

    // 建立一個皮膚來顯示所有問題和輸入框,設定為六行五列
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(6, 5)); // 設定網格佈局

    for (int j = 0; j < 30; j++) {
        panel.add(new JLabel(questionArray[j])); // 新增題目標籤
        answerFields[j] = new JTextField(10); // 建立答案輸入框
        panel.add(answerFields[j]); // 新增答案輸入框
    }

    // 獲取使用者輸入的答題時間
    String timeInput = JOptionPane.showInputDialog(null, "輸入答題時間(秒):");
    int timeLimit;

    try {
        timeLimit = Integer.parseInt(timeInput);
        if (timeLimit <= 0) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "請輸入一個有效的正整數!", "輸入錯誤", JOptionPane.ERROR_MESSAGE);
        return;
    }

    // 啟動倒數計時
    final int[] remainingTime = {timeLimit};
    Timer countdownTimer = new Timer();
    countdownTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (remainingTime[0] > 0) {
                remainingTime[0]--;
            } else {
                // 時間到時,顯示提示並結束答題
                JOptionPane.showMessageDialog(null, "時間到!", "提示", JOptionPane.WARNING_MESSAGE);
                countdownTimer.cancel(); // 倒數計時結束時取消定時器
                checkAnswers(questionArray, answers, answerFields); // 檢查答案並顯示結果
                JOptionPane.getRootFrame().dispose(); // 關閉對話方塊
            }
        }
    }, 0, 1000); // 每秒更新一次

    // 顯示問題和答案輸入框的對話方塊
    int result = JOptionPane.showConfirmDialog(null, panel, "填寫答案", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    // 停止計時器
    countdownTimer.cancel(); // 如果使用者完成答題或時間到,停止倒數計時

    if (result == JOptionPane.OK_OPTION) {
        checkAnswers(questionArray, answers, answerFields); // 檢查答案並顯示結果
    }
}

// 檢查答案並顯示結果
private static void checkAnswers(String[] questionArray, int[] answers, JTextField[] answerFields) {
    StringBuilder resultText = new StringBuilder("答題情況:\n");
    int correctCount = 0;

    for (int j = 0; j < 30; j++) {
        String userInput = answerFields[j].getText(); // 獲取使用者輸入的答案
        int userAnswer = userInput.isEmpty() ? 0 : Integer.parseInt(userInput); // 轉換使用者輸入的答案
        resultText.append(questionArray[j]).append(" ");

        // 判斷答案
        if (userInput.isEmpty()) {
            resultText.append("未作答,正確答案是:").append(answers[j]).append("\n"); // 未填寫的視為錯誤
        } else if (userAnswer == answers[j]) {
            resultText.append("正確\n");
            correctCount++;
        } else {
            resultText.append("錯誤,正確答案是:").append(answers[j]).append("\n");
        }
    }

    // 顯示校正結果
    JOptionPane.showMessageDialog(null, resultText.toString());
    // 顯示成績
    double correctRate = (correctCount / 30.0) * 100;
    JOptionPane.showMessageDialog(null, "正確率:" + String.format("%.2f", correctRate) + "%");
}

}

一、解釋Set generatedQuestions = new HashSet<>(); :

  1. Set
    Set 是一種集合型別,它用於儲存不重複的元素。與列表(如 ArrayList)不同,Set 不允許重複的值。
    指定了集合中儲存的元素型別為 String,意味著這個集合將只包含字串型別的物件。
  2. generatedQuestions
    generatedQuestions 是集合的名稱。它用來儲存生成的數學題目,以確保題目不會重複。
  3. new HashSet<>()
    HashSet 是 Set 介面的一種具體實現,基於雜湊表的原理。它提供了常數時間複雜度的插入、刪除和查詢操作。
    使用 new HashSet<>() 建立一個新的空的雜湊集合例項。
  4. 用途
    在這個程式中,generatedQuestions 用於儲存生成的數學題目,確保每道題目都是唯一的。在生成新題目時,程式會檢查該題目是否已經存在於 generatedQuestions 集合中。如果題目已經存在,程式將不會將其新增到集 閤中,從而避免重複題目。
    程式碼示例:
    import java.util.HashSet;
    import java.util.Set;

public class UniqueQuestions {
public static void main(String[] args) {
Set generatedQuestions = new HashSet<>();

    // 新增問題
    generatedQuestions.add("2 + 2 = ?");
    generatedQuestions.add("3 + 5 = ?");
    generatedQuestions.add("2 + 2 = ?"); // 重複的問題,不會被新增

    // 輸出所有問題
    for (String question : generatedQuestions) {
        System.out.println(question);
    }
    
    // 輸出問題的數量
    System.out.println("問題總數: " + generatedQuestions.size());
}

}

二、解釋JTextField[] answerFields = new JTextField[30]; :

  1. JTextField[]
    JTextField 是 Java Swing 中的一個類,用於建立文字輸入框。使用者可以在文字框中輸入文字內容。
    JTextField[] 表示一個 JTextField 物件的陣列。這意味著你將建立多個文字輸入框,每個文字框可以儲存使用者輸入的字串。
  2. answerFields
    answerFields 是陣列的名稱。在這個上下文中,它可以表示用於儲存使用者輸入答案的文字框。
  3. new JTextField[30]
    new JTextField[30] 建立一個新的 JTextField 陣列,大小為 30。這意味著你可以儲存最多 30 個 JTextField 物件。
    陣列的每個元素在初始化時都是 null,你需要分別建立 JTextField 物件並將它們分配給陣列的每個元素。
    用途:
    這個陣列可以用於處理多個文字輸入,例如在一個圖形使用者介面(GUI)中,使用者可以輸入答案(例如數學問題的答案)。透過陣列,可以輕鬆地管理和訪問這些文字框。
    示例
    以下是一個簡單的示例,展示瞭如何建立 JTextField 陣列,並在 JFrame 中新增這些文字框:
    import javax.swing.;
    import java.awt.
    ;

public class AnswerInputExample {
public static void main(String[] args) {
// 建立一個 JFrame
JFrame frame = new JFrame("Answer Input Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(30, 1)); // 設定網格佈局

    // 建立一個 JTextField 陣列
    JTextField[] answerFields = new JTextField[30];

    // 建立並新增 JTextField 到陣列和 JFrame
    for (int i = 0; i < answerFields.length; i++) {
        answerFields[i] = new JTextField("Answer " + (i + 1));
        frame.add(answerFields[i]); // 將 JTextField 新增到 JFrame
    }

    // 設定 JFrame 尺寸並可見
    frame.setSize(400, 600);
    frame.setVisible(true);
}

}

相關文章