英文:
Why I cannot use string methods inside groovy closure? - no candidate for method call
问题
I have simple hashmap and want to manipulate it but IDE does not recognize the methods. Completely new to Groovy so not sure what is wrong.
def percentages = [
    "x1" : "20%",
    "x2" : "30%",
    "x3" : "0.4",
    "x4" : "50%",
    "x5" : "0.6"
]
percentages.each { key, val ->
    if (val.endsWith("%")) {
        val = val[0..-2]
        println val
    }
}
英文:
I have simple hashmap and want to manipulate it but IDE does not recognize the methods. Completely new to Groovy so not sure what is wrong.
    def percentages = [
        "x1" : "20%",
        "x2" : "30%",
        "x3" : "0.4",
        "x4" : "50%",
        "x5" : "0.6"]
    percentages.each {
    val ->
         if(val[2].endsWith("%")) {
        val[2].deleteCharAt(val.length()-1)
        println val
    }
}
答案1
得分: 1
When you do percentages.each, you iterate over the map, and each element is of type java.util.Map.Entry. Here is probably what you need:
import java.util.Map.Entry
def percentages = [
    "x1": "20%",
    "x2": "30%",
    "x3": "0.4",
    "x4": "50%",
    "x5": "0.6"]
percentages.each { Entry<String, String> val ->
    if (val.value.endsWith("%")) {
        val.value = val.value.substring(0, val.value.length() - 1)
        println val
    }
}
or even more compact, as @daggett suggested:
def percentages = [
    "x1": "20%",
    "x2": "30%",
    "x3": "0.4",
    "x4": "50%",
    "x5": "0.6"]
percentages.each { k, v ->
    if (v.endsWith("%")) {
        percentages[k] = v.substring(0, v.length() - 1)
        println percentages[k]
    }
}
英文:
When you do percentages.each you iterate over map and each element is java.util.Map.Entry. Here is probably what you need:
import java.util.Map.Entry
def percentages = [
    "x1": "20%",
    "x2": "30%",
    "x3": "0.4",
    "x4": "50%",
    "x5": "0.6"]
percentages.each { Entry<String, String> val ->
    if (val.value.endsWith("%")) {
        val.value = val.value.substring(0, val.value.length() - 1)
        println val
    }
}
or even more compact, as @daggett suggested:
def percentages = [
    "x1": "20%",
    "x2": "30%",
    "x3": "0.4",
    "x4": "50%",
    "x5": "0.6"]
percentages.each {k, v ->
    if (v.endsWith("%")) {
        percentages[k] = v.substring(0, v.length() - 1)
        println percentages[k]
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论