2017-04-04 75 views
1

我是新來的Groovy和在測試下面的代碼:檢查字符串列表在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 

當控制檯運行,它會拋出下面的異常:

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) 

是什麼錯誤的意思是?

我做這個解決問題:

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

但真的想了解上述錯誤。 謝謝, 保羅

回答

1

值呀誤差並不明顯;反正country_list[item].toUpperCase()是造成這個問題,我想你想用item.toUpperCase()來代替。

試試這個:

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

運行在groovyConsole中here的解決方案。

+0

明白了。非常感謝! –

2

這是因爲,你有名單country_list。 但使用地圖符號來獲取值。

sgfor循環列表中的第一個元素。它假設從country_list獲取sg財產,並且沒有這樣的財產,sg僅僅是相反的價值。

因此,誤差是obivious:

ERROR groovy.lang.MissingPropertyException: 異常評價屬性 'SG' 的java.util.ArrayList的,原因是:groovy.lang.MissingPropertyException:沒有這樣的屬性: SG類:java.lang.String中

你可以簡單的檢查/斷言使用下面的腳本:

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" 
+0

這條線的目的是什麼? '// assert isPH,'列表中沒有ph' 腳本可以在沒有它的情況下運行。 –

+0

'?和:'如果和其他情況一樣工作。它可以運行而不斷言。但如果腳本失敗了,你怎麼樣?這就是爲什麼'assert for isPH true' – Rao

+1

'it.toUpperCase()=='PH'? true:false'只是'it.toUpperCase()=='PH''。當OP沒有短路時,我認爲這樣做會是一個好習慣:'country_list.find {it.toUpperCase()=='PH'}'給你匹配元素(truthy)或'如果不在列表中,則爲null。 – cfrick

2

country_list[item]更改爲item

這是因爲Groovy看起來財產sgArrayList類,因爲常規Object.getAt(String property)方法返回的property

+0

這工作。謝謝 ! –