我很清楚这段代码很糟糕。我刚刚做到了,所以我可以尝试不同的 Swing 东西。这是一个有趣的问题。这将创建 4 个按钮,一个用于加法、减法、除法和乘法。乘法和加法完美无缺,完全没有问题,但是当用户尝试减去它时,它总是返回 0。当用户尝试除法时,它总是根据输入返回 1 或 1.0。我想不通。这是代码:
(ns rayne.main
(:gen-class)
(:import (javax.swing JFrame JTextField JButton JOptionPane)
(java.awt.event ActionListener)
(java.awt GridLayout)))
(def numbers (ref []))
(def times-clicked (ref 0))
(defn calc [nseq op]
(let [n1 (first nseq)
n2 (last nseq)]
(cond
(= op "+") (+ n1 n2)
(= op "*") (* n1 n2)
(= op "-") (- n2 n1)
(= op "/") (/ n1 n2))))
(defn add-op-button [op text button]
(.addActionListener button
(proxy [ActionListener] []
(actionPerformed [e]
(dosync
(ref-set times-clicked (inc @times-clicked))
(if (= @times-clicked 2)
(do
(let [result (.toString (calc @numbers op))
result2 (read-string result)]
(.setText text result)
(ref-set numbers [])
(ref-set times-clicked 0)))
(do
(ref-set numbers (conj @numbers (read-string (.getText text))))
(.setText text ""))))))))
(defn -main []
(let [frame (JFrame. "Calculator")
add-button (JButton. "+")
sub-button (JButton. "-")
mul-button (JButton. "*")
div-button (JButton. "/")
clr-button (JButton. "Clear")
text-field (JTextField.)]
(add-op-button "+" text-field add-button)
(add-op-button "-" text-field sub-button)
(add-op-button "*" text-field mul-button)
(add-op-button "/" text-field div-button)
(doto frame
(.setLayout (GridLayout. 1 5))
(.add text-field)
(.add add-button)
(.add sub-button)
(.add mul-button)
(.add div-button)
(.setSize 500 100)
(.setVisible true))))
由于复制粘贴和动态格式化,缩进可能搞砸了,但确实如此。我再一次知道代码很糟糕。