从列表中打印特定字段

时间:2017-11-22 08:42:08

标签: groovy

请帮助打印assetNumber。需要搜索特定的资产名称并使用groovy中的列表打印其关联的assetNumber。

目前,它没有打印价值。一旦输入搜索条件,它就会出现。

class Main
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
List list = new ArrayList()
Asset asset = new Asset()
def name
def assetNumber
def assigneeName
def assignedDate
def assetType
String userInput = "Yes"
while(userInput.equalsIgnoreCase("Yes"))
{
println "Enter the asset details:"
asset.name = br.readLine()
asset.assetNumber= Integer.parseInt(br.readLine())
asset.assigneeName = br.readLine()
asset.assignedDate = Date.parse('dd/MM/yyyy', br.readLine())
list.add(asset)
println "Do you want to continue(yes/no)"
userInput = br.readLine()
}
println "Enter the asset type:"
assetType = br.readLine()
println "Asserts with type "+assetType+":"
def items = list.findAll{p->p.name == assetType }
items.each { println it.assetNumber }
}
}
 class Asset
{
def name
def assetNumber
def assigneeName
def assignedDate
}

1 个答案:

答案 0 :(得分:0)

您正在覆盖Asset对象中的值,然后每次都将相同的对象添加到列表中

如果你在循环中创建一个新资产(而不是在它之外),它应该可以工作......

这样的事情:

import groovy.transform.*

class Main {
    static main(args) {
        def console = System.console()
        def list = []
        while (true) {
            def name = console.readLine 'Enter the asset name:'
            def number = console.readLine 'Enter the asset number:'
            def assignee = console.readLine 'Assignee name:'
            def date = console.readLine 'Date (dd/MM/yyyy):'
            list << new Asset(
                name: name,
                assetNumber: Integer.parseInt(number),
                assigneeName: assignee,
                assignedDate: Date.parse('dd/MM/yyyy', date)
            )
            if ('Y' != console.readLine('Enter another (y/n):')?.take(1)?.toUpperCase()) {
                break
            }
        }
        def type = console.readLine 'Enter the asset type:'
        println "Assets with type $type:"
        list.findAll { p -> p.name == type }
            .each { println it.assetNumber }
    }

    @Canonical
    static class Asset {
        def name
        def assetNumber
        def assigneeName
        def assignedDate
    }
}