Clojure中的简单猜谜游戏无法正常工作

时间:2018-12-07 15:22:19

标签: clojure functional-programming lisp

我是Clojure的新手。作为练习的一部分,我编写了一个简单的猜测游戏,用户必须猜测程序选择的1-100之间的随机数。我有一个基本的版本正在工作(代码片段1)。现在,我想通过允许用户输入1到100之间的整数来对此进行改进。但是,为避免用户输入字符串而编写的代码不起作用(代码段2),但是该代码不起作用,不不管我尝试什么。

代码段1(有效)

(ns guessing-game2.core
     (:gen-class))

(defn -main []
  (let [my-number (inc (rand-int 100))]
    (println "I have a number between 1 and 100, guess it: ")
    (loop [times 1]
      (let [guess (Integer/parseInt (read-line))]
        (if (= guess my-number)
          (do
            (println "You have found it in " times " tries!")
            times)

          (do
            (cond
            (< guess my-number) (println "My number is bigger, guess again: ")
            (> guess my-number) (println "My number is smaller, guess again: "))
        (recur (inc times))))))))

代码段2(无效)

(ns guessing-game.core
  (:gen-class))

(defn -main []
  (let [my-number (inc (rand-int 100))]
    (println "I have a number between 1 and 100, guess it: ")
    (loop [times 1]
      (let [guess (Integer/parseInt (read-line))]
      (if (and (integer? guess) 
              (< guess 100))
        (if (= guess my-number)
          (do
            (println "You have found it in " times " tries!")
            times)

          (do
            (cond
              (< guess my-number) (println "My number is bigger, guess again: ")
              (> guess my-number) (println "My number is smaller, guess again: "))))

      (print "Please enter a number")
      (recur (inc times))

    )
    ))))      

1 个答案:

答案 0 :(得分:0)

您需要在if之外recur

(ns guessing-game.core
  (:gen-class))

(defn -main []
  (let [my-number (inc (rand-int 100))]
    (println "I have a number between 1 and 100, guess it: ")
    (loop [times 1]
      (let [guess (Integer/parseInt (read-line))]
      (if (and (integer? guess) 
              (< guess 100))
        (if (= guess my-number)
          (do
            (println "You have found it in " times " tries!")
            times)

          (do
            (cond
              (< guess my-number) (println "My number is bigger, guess again: ")
              (> guess my-number) (println "My number is smaller, guess again: "))))

      (print "Please enter a number")) ;; <-- moved bracket to here 
    (recur (inc times))  
    ))))