views:

143

answers:

1

This is about a very basic program I'm writing in Groovy.

I have defined a map inside a method:

  def addItem() 
  {
    print("Enter the item name: ")
    def itemName = reader.readLine()
    print("Enter price : ")
    def price = reader.readLine()
    print("Enter barcode : ")
    def barcode = reader.readLine()
    data[itemName] = ['price' : price, 'barcode' : barcode]
  }

The problem is I don't know how to update just one value inside a different method. Here's what I tried:

  def updatePrice() 
  {
    print("Enter the item name: ")
    def itemName = reader.readLine()
    print("Enter new price : ")
    def price = reader.readLine()
    data[itemName] = ['price' : price]
  }

This sort of works. It changes the value of price but it also changes the barcode value to 'null' presumably because it's being overwritten with...nothing.

Basically I need the code to change the price but leave the barcode as it is. Any ideas on how I can do this?

Sorry if this is a ridiculously elementary question but I'm still very much a newbie at programming.

+4  A: 

What you did is replacing the whole map instance for the given item. There are several ways to change the value for a key in a map. You could do it the traditional Java way:

data[itemName].set('price', price)

You could access it like you did for the itemName using square brackets:

data[itemName].['price'] = price

Or you can access the values of maps using the Map.keyname notation. So alternatively you could simply write:

data.itemName.price = price

This also works when you want to retrieve the value for a given key:

println data.itemName.price // prints the price value for an item
Christoph Metzendorf
Works perfectly! Thank you very much!
Simba