简体   繁体   English

在Groovy中检查字符串列表

[英]Checking List of String in Groovy

I'm new to groovy and have the following code in testing: 我是groovy的新手,在测试中有以下代码:

groovy> def country_list = [] 
groovy> country_list =['sg', 'ph', 'hk'] 
groovy> for (String item : country_list) { 
groovy>     println item 
groovy>     if (country_list[item].toUpperCase() == "PH") 
groovy>         isPH = true 
groovy> } 
groovy> println isPH 

When run in console, it throws the exception below: 在控制台中运行时,它将引发以下异常:

sg
Exception thrown

groovy.lang.MissingPropertyException: Exception evaluating property 'sg' for java.util.ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: sg for class: java.lang.String
at ConsoleScript6.run(ConsoleScript6:5)

What does the error mean ? 错误是什么意思?

I do resolve the issue by this : 我确实通过以下方式解决了这个问题:

isPH = ('PH' in country_list) || ('ph' in country_list)

But really want to understand the error above. 但是真的很想了解上面的错误。 Thanks, Paul 谢谢保罗

That is because, you have list country_list . 那是因为,您有list country_list But using map notation to fetch the value. 但是使用映射符号来获取值。

sg is the first element in the list of for loop. sgfor循环列表中的第一个元素。 It was assuming to fetch the property sg from country_list and there is no such property and sg only value on the contrary. 假定要从country_list获取属性sg ,而没有这样的属性,而sg仅具有相反的值。

Hence the error which is obivious: 因此,错误是显而易见的:

ERROR groovy.lang.MissingPropertyException: Exception evaluating property 'sg' for java.util.ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: sg for class: java.lang.String 错误groovy.lang.MissingPropertyException:java.util.ArrayList的异常评估属性“ sg”,原因:groovy.lang.MissingPropertyException:无此类属性:类:java.lang.String的sg

You can simple check / assert using below script: 您可以使用以下脚本简单地检查/声明:

def country_list =['sg', 'ph', 'hk']
def isPH = country_list.find { it.toUpperCase() == 'PH' } ? true : false
assert isPH, 'No ph in the list'
println "Is country list contains ph ? $isPH"

Change country_list[item] to item . country_list[item]更改为item

This is because groovy looks property sg for class ArrayList since groovy Object.getAt(String property) method returns the value of property 这是因为groovy查找ArrayList类的sg属性,因为groovy Object.getAt(String property)方法返回property的值

Yeah the error is not obvious; 是的,错误并不明显; anyways the country_list[item].toUpperCase() is causing the issue, I guess you want to use item.toUpperCase() instead. 无论如何, country_list[item].toUpperCase()引起了问题,我想您想改用item.toUpperCase()

Try this: 尝试这个:

def country_list = [] 
 country_list =['sg', 'ph', 'hk'] 
 for (String item : country_list) { 
     println item 
     if (item.toUpperCase() == "PH") 
         isPH = true 
 } 
 println isPH 

Run the solution on groovyConsole here . 运行groovyConsole中的解决方案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM