LoginSignup
3
3

More than 5 years have passed since last update.

Groovyで標準入力を繰り返し受け取る

Last updated at Posted at 2016-02-10

目標

  • 標準入力から文字を受け取りたい
  • 正しい形式の入力が来るまでリトライしたい

結論

標準入力から読み取った後に

  • eachブロックで受けるのはダメ(eachから抜けられなくなる)。
  • anyブロックにて受ければOK。

コード

環境

Java 8
Groovy 2.4.5

判定用メソッド

Utility.groovy
@Singleton
class Utility {
    /**
     * ユーザに続行するかを問う
     * 標準入力:Y  続行する
     *         :n  続行しない(exitする)
     *         :他 再入力
     * @return true  続行可能
     */
    def askContinue() {
        print "continue? [Y/n]"
        def stdin = new BufferedReader(new InputStreamReader(System.in))

        stdin.lines().any{ line -> 
            if(line.equals("Y")) {
                return true
            } else if(line.equals("n")) {
                System.exit(1)
            } else {
                println "incorrect word."
                print "continue? [Y/n]"
            }
        }
    }
}

呼び出し用スクリプト

test.groovy
Utility.instance.askContinue()

実行例

$ groovy test.groovy 
continue? [Y/n]a
incorrect word.
continue? [Y/n]b
incorrect word.
continue? [Y/n]c
incorrect word.
continue? [Y/n]d
incorrect word.
continue? [Y/n]Y
$ echo $?
0

$ groovy test.groovy 
continue? [Y/n]n
$ echo $?
1

参考

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3