Clojure GUI计算器." - "始终返回0,"/"始终返回1

Ray*_*yne 3 java swing clojure

我很清楚这段代码太可怕了.我刚刚做到了所以我可以尝试不同的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))))
Run Code Online (Sandbox Code Playgroud)

由于复制粘贴和动态格式化,缩进可能搞砸了,但它确实存在.我再一次知道代码太可怕了.

Dan*_*ant 6

用户第二次单击按钮时,该数字不会添加到列表中numbers,因此您在calc一个元素的列表上进行操作.

由于列表只有一个元素,第一个元素(n1)和最后一个元素(n2)是相同的东西,和

x / x => 1
x - x => 0
Run Code Online (Sandbox Code Playgroud)

我很惊讶你的加法和乘法工作......: - /

我想你可以通过移动的更新解决这个问题@numbers之前,到if:

(ref-set numbers (conj @numbers (read-string (.getText text))))
(if (= @times-clicked 2)
Run Code Online (Sandbox Code Playgroud)

否则移动inc的种类调和@times-clicked为后if.