目標
- 標準入力から文字を受け取りたい
- 正しい形式の入力が来るまでリトライしたい
結論
標準入力から読み取った後に
- 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