问题描述:

I am making a "vending machine" and I need to index the total sales, and the amount of drinks left in the machine. Right now I have it set up when the user click on the picture of the soda, it will do the logic. Here is the full class:

namespace _8_11

{

struct Drink

{

public string Name;

public float Price;

public int Amount;

}

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

object[,] Cola = new object[,]

{

{"Coke", 1.00f, 20 },

{"Beer", 1.00f, 20 },

{"Sprite",1.00f, 20 },

{"Grape", 1.50f, 20 },

{"Cream", 1.50f, 20 }

};

float total = 0.00f;

private void pictureBox1_Click(object sender, EventArgs e)

{

Drink Coke = new Drink();

Coke.Name = (string)Cola[0, 0];

Coke.Price = (float)Cola[0, 1];

Coke.Amount = (int)Cola[0, 2];

if (Coke.Amount > 1 && Coke.Amount <= 20)

{

Coke.Amount -= 1;

total += Coke.Price;

cokeLeftLabel.Text = Coke.Amount.ToString();

totalSalesLabel.Text = total.ToString("c");

}

else {

MessageBox.Show("We are out of Coke!");

}

}

}

}

The main problem is that the code:

Drink Coke = new Drink();

Coke.Name = (string)Cola[0, 0];

Coke.Price = (float)Cola[0, 1];

Coke.Amount = (int)Cola[0, 2];

When ever the user click the picture, these variables are reset. I need to initialize these variables outside of the clicked method, but when i try to move them outside this method it gives a compiling error "Coke.Amount does not exist in this current context".

I fixed it. Here is the revised code:

if (Coke.Amount > 0 && Coke.Amount <= 20)

{

Coke.Amount -= 1;

Cola[0, 2] = Coke.Amount;

total += Coke.Price;

cokeLeftLabel.Text = Coke.Amount.ToString();

totalSalesLabel.Text = total.ToString("c");

}

网友答案:

You could try something like this:

List<Drink> drinks = new List<Drink>
{
  new Drink("Cola", 1.5f 20),
  //...
}

private void pictureBox1_Click(object sender, EventArgs e)
{
  Drink drink = drinks[0];//Get the correct drink
  drink.Amount--;
   //...      
网友答案:

I usually create a custom picture box like the code below

public class DrinkPictureBox : PictureBox
{
    Drink drink = new Drink();

    public DrinkPictureBox(string Name, float Price, int Amount)
    {
        drink.Name = Name;
        drink.Price = Price;
        drink.Amount = Amount;
    }
}
网友答案:

Try pulling the declaration of the variable into the class

public partial class Form1 : Form
    {
        internal Drink Coke = new Drink();
        public Form1()
        {
            InitializeComponent();
            Coke.Name = (string)Cola[0, 0];
            Coke.Price = (float)Cola[0, 1];
            Coke.Amount = (int)Cola[0, 2];
        }
    }

Then, declare the initial constraints during Form1. This should give visibility to both Form and Events. I tried to do this, and have no issues from it.

相关阅读:
Top