如何实现控制台输入程序?

47 views
Skip to first unread message

hl p

unread,
Apr 30, 2014, 11:18:18 AM4/30/14
to cn-cl...@googlegroups.com
看完两本clojure的书,缺少实现例子,找了一下初级的例子,高手勿喷:)

        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while ((line = readLine(reader)) != null) {

                System.err.println(line );

        }
    private static String readLine(final BufferedReader reader) throws IOException {
        System.out.println("Type a message to send:");
        return reader.readLine();
    }

java代码是从控制台不断输入字符串并打印。

clojure 代码

(def reader (BufferedReader. (InputStreamReader. ( System/in))))

(defn readline []
  (println "Type a message to send:")
  (.readLine reader))

(def line readline)
;;;;这一段代码一直没写明白,求代码。。。。
(defn loopread []
  (loop [strline line ]
    (strline)
    (if (nil? strline)
      strline
      (println strline))))


dennis zhuang

unread,
Apr 30, 2014, 11:53:02 AM4/30/14
to nullnull

read-line就够了,标准库函数

--
中文社区博客:http://blog.clojure.cn/
中文问答网站:http://ask.clojure.cn/
中文邮件列表:https://groups.google.com/d/forum/cn-clojure?hl=zh-CN
---
您收到此邮件是因为您订阅了Google网上论坛中的“CN-Clojure”论坛。
要退订此论坛并停止接收此论坛的电子邮件,请发送电子邮件到cn-clojure+...@googlegroups.com
要发帖到此论坛,请发送电子邮件至cn-cl...@googlegroups.com
通过http://groups.google.com/group/cn-clojure访问此论坛。
要查看更多选项,请访问https://groups.google.com/d/optout

hl p

unread,
May 1, 2014, 7:59:22 PM5/1/14
to cn-cl...@googlegroups.com
是,已经替换了,问题出在循环结构上,有点晕了。

在 2014年4月30日星期三UTC+8下午11时53分02秒,dennis写道:

read-line就够了,标准库函数

要退订此论坛并停止接收此论坛的电子邮件,请发送电子邮件到cn-clojure+unsubscribe@googlegroups.com

Seth Yuan

unread,
May 8, 2014, 8:54:43 PM5/8/14
to cn-cl...@googlegroups.com
你是想用loop recur吧?例如:

(loop [line (readline)]
  (when-not (nil? line)
    (println line)
    (recur (readline))))

hl p

unread,
May 10, 2014, 4:23:42 AM5/10/14
to cn-cl...@googlegroups.com
(defn readline []
  (println (format "Type a message to send: %s" (read-line)))
  (flush))


(defn loopread []
  (loop []
    (readline)
    (recur)))

IDEA编程环境
这是我写的版本,但是当点击stop后 后台又打印很多
Type a message to send: null
Type a message to send: null
Type a message to send: null
Type a message to send: null
Type a message to send: null
Type a message to send: null
。。。。。。。。。。

不理解为什么这样?
一时半会儿还不适应这中编程模式。。。。。



在 2014年5月9日星期五UTC+8上午8时54分43秒,Seth Yuan写道:

Seth Yuan

unread,
May 14, 2014, 8:45:23 PM5/14/14
to cn-cl...@googlegroups.com
loop recur是循环控制的高级抽象,你可以用loop recur模拟各类其它语言中的循环,例如while, for, foreach, continue, break等等。所以loop recur是非常强大的!

loop创建一个循环,并且声明+初始一些只在loop内可见的“变量”,这些“变量”包括循环判断条件、最终结果值等。至于loop内代码循环与否是由recur决定的,当遇到recur时就会进入下一个循环(迭代)。但是recur必须是最后一个表达式,所以所有需要变化的值都必须声明在loop里,这样在调用recur时就可以通过传递新值的方式实现“变量”的效果了。

例如你的loop没有结束条件,recur每次都会被调用到,也就是一个无限循环。
Reply all
Reply to author
Forward
0 new messages