Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String error when accessing element from a Map

When looping over weapons, I get the following error:

var weapons = {}
    weapons["Bow"] = 5
    weapons["Sword"] = 15
    weapons["Battle-Axe"] = 20

for (item in weapons.keys) {
    System.print("%(item) Damage: " + (weapons[item]))
}
Right operand must be a string.
[compile line 7] in (script)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When you do weapons[item], you’re accessing a number (damage) not a string. You need to use %():

for (item in weapons.keys) {
  System.print("%(item) Damage: %(weapons[item])")
}

# Output:
Sword Damage: 15
Bow Damage: 5
Battle-Axe Damage: 20
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading