3

我很清楚这段代码很糟糕。我刚刚做到了,所以我可以尝试不同的 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))))

由于复制粘贴和动态格式化,缩进可能搞砸了,但确实如此。我再一次知道代码很糟糕。

4

2 回答 2

6

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

由于列表只有一个元素,所以第一个元素 ( n1) 和最后一个元素 ( n2) 是相同的,并且

x / x => 1
x - x => 0

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

我认为您可以通过将更新移动@numbers到之前来解决此问题if

(ref-set numbers (conj @numbers (read-string (.getText text))))
(if (= @times-clicked 2)

否则将increment@times-clicked移到if.

于 2009-03-17T00:32:31.437 回答
4

看起来 add 只是将数字添加到自身,而乘法函数实际上只是将第一个数字平方。

于 2009-03-17T00:37:00.367 回答