blaces
blaces

Reputation: 495

C# method give me an extra Console.WriteLine

I have a little problem, in my source code I don't see why is my ToUpload method give me an extra console.writeLine in the Console window. (write out the beer object)

When I call the ToUpload method, and the beer is in the beers dictionary, it give me an extra Console.WriteLine, where write out the beer object at the Console. And I don't know why.

This is my output:

and i want this:

Here is the Beer class:

public class Beer
{
    string name;
    int price; 
double alcohol;

public string Name { get { return name; } }

public int Price{ get; set; }

public double AlkoholTartalom { get { return alcohol; } }

public Beer(string name, int price, double alcohol)
{
    // ide írja a kódot
    this.name = name;
    this.price = price;
    this.alcohol = alcohol;
}

public override bool Equals(object obj)
{
    if (obj is Beer)
    {
        Beer other = (Beer)obj;
        return this.name == other.name;
    }
    return false;
}

public override string ToString()
{
    return this.Name + " " + this.Price+ " " + this.AlkoholTartalom;
}
}

Upvotes: 0

Views: 171

Answers (2)

Joe
Joe

Reputation: 2659

Depending on what type beers is you can just do this:

public void ToUpload(Beer beer, int dl)
{
    int d = 0;
    if(beers[beer] != null)
        d = beers[beer];

    beers[beer] = d + dl;
}

I know that HashTables will automatically either update or add to the dictionary based on whether or not the key was found when they are accessed this way.

Upvotes: 0

Katu
Katu

Reputation: 701

You are missing "Else" at the ToUpload method.

// if this beer in the beers, update the value
if (s != null)
{
    beers[s] = d + dl;
}
else  // Add this 
    beers.Add(beer, dl); // IDictionary beers = new Dictionary

From what i see, this should fix it. You are adding the beer to dictionary, even thou you should just update it.

Upvotes: 2

Related Questions