Следующий код:
def home = System.properties['user.home']
def file = new File("${home}/Desktop/invoicedetails.csv")
if (!file.isFile() && !file.createNewFile()) {
println "Failed to create file: $file"
return
}
int lineCount = prompt("Enter the number of items") as Integer
file.withPrintWriter { pw ->
lineCount.times { i ->
readRecord(i, pw)
}
}
def readRecord(i, pw) {
println "- enter details for item ${i+1} -"
def line = []
line << prompt("name")
line << prompt("price").toDouble()
line << prompt("quantity").toInteger()
pw.println(line.join(','))
}
def prompt(question) {
System.console().readLine("${question} > ")
}
должен решить вашу проблему.Ниже примера запуска:
~> groovy solution.groovy
Enter the number of items > 2
- enter details for item 1 -
name > Jet Pack
price > 9999.99
quantity > 2
- enter details for item 2 -
name > Plane Desnaking Kit
price > 24999.99
quantity > 1
~> cat ~/Desktop/invoicedetails.csv
Jet Pack,9999.99,2
Plane Desnaking Kit,24999.99,1
~>
Следует отметить, что если кто-то, кроме вас, собирается выполнить это, вам, вероятно, следует включить обработку ошибок для таких вещей, как люди, вводящие one
при запросе количества и т. Д.Это может быть выполнено с помощью чего-то вроде следующего (остальная часть кода остается прежней):
def readRecord(i, pw) {
println "- enter details for item ${i+1} -"
def line = []
line << prompt("name")
line << prompt("price", Double)
line << prompt("quantity", Integer)
pw.println(line.join(','))
}
def prompt(question, clazz=String) {
boolean valid = false
def answer
while (!valid) {
try {
answer = System.console().readLine("${question} > ").asType(clazz)
valid = true
} catch (Exception e) {
println "-> invalid answer format for type ${clazz.simpleName}"
println "-> please try again!"
}
}
answer
}
с примером выполнения:
~> groovy solution.groovy
Enter the number of items > 1
- enter details for item 1 -
name > Jet Pack
price > a million bucks
-> invalid answer format for type Double
-> please try again!
price > 1234.23343434
quantity > a lot
-> invalid answer format for type Integer
-> please try again!
quantity > 10
~>