English 中文(简体)
Changing the value in a map in Groovy
原标题:

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.

问题回答

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




相关问题
Selecting Links in Google Maps InfoWindows w/ jQuery

In my web app, I am using jQuery to select all the links on the page and intercept where they go to so that I can switch to a different part of the page with AJAX. The problem is that some of these ...

Add custom control to Subgurim Maps

Is it possible to add a custom control to the GMap control in the Subgurim library? I see that I can add a GControl with the GMap.AddControl method. I tried to create a custom GControl by ...

Changing the value in a map in Groovy

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(...

Best way to store and retrieve this..?

I ve been trying all night, and talk of maps, arrays, vectors and hash_maps have filled my head. im just confused now. i posted a previous question here: C++ map really slow? problem was fixed but it ...

热门标签