Beginner Programmer Help

Started by
9 comments, last by Khaiy 11 years ago

I am trying to make a simple program that has the user buy items, sell items, and list their items. Just trying to practice what I have learned thus far. I have made a class to buy items, and a class to list the items. The problem I am encountering is when the "buy" class is done running and has stored the items in a playersInventory array, that data in the heap gets erased before the "list" class can list what the player has bought. Any help with this would be much appreciated, as well as any and all critique on my code.

Program Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuySell_Gear
{
    class Program
    {
        static void Main(string[] args)
        {
            MainMenu mainMenu = new MainMenu();

            mainMenu.MenuScreen();
        }
    }
}

MainMenu struct


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuySell_Gear
{
    struct MainMenu
    {
        static int MainMenuMethod()
        {
            Console.Clear();
            Console.WriteLine("Select what you would like to do:");
            Console.WriteLine("1. Buy");
            Console.WriteLine("2. Sell");
            Console.WriteLine("3. List");
            Console.WriteLine("4. Exit");
            return Convert.ToInt32(Console.ReadLine());
        }

        public void MenuScreen()
        {
            int menuSelection = 0;
            while (menuSelection != 4)
            {
                menuSelection = MainMenuMethod();
                Buy buy = new Buy();
                List list = new List();

                if (menuSelection == 1)
                {
                    buy.BuyStuff();
                }
                else if (menuSelection == 2)
                {
                    break;
                }
                else if (menuSelection == 3)
                {
                    list.GenerateList();
                }
                else if (menuSelection == 4)
                {
                    break;
                }
                else
                {
                    Console.Clear();
                    Console.WriteLine("\t\t***Invalid Entry***");
                    Console.ReadLine();
                }
            }
        }
    }
}

Buy class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuySell_Gear
{
    class Buy
    {
        private string[] itemsForSale = new string[] { "M-16", "Grenade", "Flak Jacket", "Kevlar", "K-Bar" };
        private int[] pricesForItems = new int[] { 300, 90, 100, 50, 20 };
        private string[] playersInventory = new string[5];  //Player can only carry 5 items
        private int[] playersInventoryIndex = new int[5];
        private int playersMoney = 500;
        private int playersSelection = 0;
        private int placeItemInIndexOfPlayersInventory = 0;

        //Begin Constructors

        public string[] PlayersInventory
        {
            get { return playersInventory; }
            set { playersInventory = value; }
        }

        public int[] PricesForItems
        {
            get { return pricesForItems; }
        }

        public int[] PlayersInventoryIndex
        {
            get { return playersInventoryIndex; }
            set { playersInventoryIndex = value; }
        }

        public int PlayersMoney
        {
            get { return playersMoney; }
            set { playersMoney = value; }
        }

        private int PlayersSelection
        {
            get { return playersSelection; }
            set { playersSelection = value; }
        }

        //Begin Methods:

        public void BuyStuff()
        {
            while (PlayersSelection != 21)
            {    
                Console.Clear();
                Console.WriteLine("What would you like to buy:(type 22 to exit)");
                int list = 1;
                    for (int index = 0; index < itemsForSale.Length; index++)
                    {
                        Console.WriteLine(list + ". " + itemsForSale[index] + " costs $" + pricesForItems[index]);
                        ++list;
                    }
                playersSelection = Convert.ToInt32(Console.ReadLine()) - 1;

                if (PlayersSelection == 21)
                    {
                        break;
                    }

                else if (PlayersInventory.Length == placeItemInIndexOfPlayersInventory)
                    {
                        Console.Clear();
                        Console.WriteLine("You cannot carry any more objects");
                        Console.ReadLine();
                        break;
                    }

                else if (PlayersMoney < PricesForItems[playersSelection]) 
                    {
                        Console.Clear();
                        Console.WriteLine("\nYou do not have enough money");
                        Console.ReadLine();
                        continue;
                    }
                else
                    {
                        PlayersInventory[placeItemInIndexOfPlayersInventory] = itemsForSale[playersSelection];
                        PlayersInventoryIndex[placeItemInIndexOfPlayersInventory] = PlayersSelection;
                        ++placeItemInIndexOfPlayersInventory;
                        PlayersMoney -= PricesForItems[playersSelection];

                        Console.WriteLine("You just bought a/n " + itemsForSale[playersSelection] + " for $" + pricesForItems[playersSelection]);
                        Console.WriteLine("You have $" + PlayersMoney + " left.");
                        Console.ReadLine();
                    }                
            }
        }
    }
}

List Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuySell_Gear
{
    class List
    {
        public void GenerateList()
        {
            Buy buy = new Buy();
            Console.Clear();
            int list = 1;
            for (int index = 0; index < buy.PlayersInventory.Length; index++)
            {
                if (buy.PlayersInventory[index] == null)
                {
                    Console.WriteLine(list + ". empty");
                    ++list;
                    continue;
                }
                else
                {
                    Console.WriteLine(list + ". " + buy.PlayersInventory[index]);
                    ++list;
                }
            }
            Console.ReadLine();
        }
    }
}

Cpl Alt, Travis A

USMC

Advertisement

I see a couple of things. First, it looks like the playersInventory field only exists in an instantiation of the Buy class. Second, you are creating a couple of different Buy objects, one in the MenuScreen method of the MainMenu structure and another in the GenerateList method of the List class. When you are displaying the player's inventory you're displaying the playersInventory field of the Buy object created in GenerateList(), not the one in the Buy object created in MainMenu. List's Buy object never has its BuyStuff method called and so its playersInventory field will never have any strings in it.

I think that your class layout might be causing some confusion. You have two classes, Buy and List, both of which currently exist only to execute routines. There's nothing inherently wrong with that, but the playersInventory field doesn't really belong in such a class. There are lots of ways to arrange things, but I would suggest creating the playersInventory array in Main. From there you can try things like passing it into the appropriate methods in Buy and List. Even better would be to create an Inventory class which has methods that allow it to do the things you want (methods like Inventory.ListItems(), Inventory.AddItem(), etc.).

I would also suggest that you not name a class "List", as List is already a type in C#.

-------R.I.P.-------

Selective Quote

~Too Late - Too Soon~

Instead of having a seperate class to list the members of the array, it might be easier to call a mthod in your buy class which lists the items in the players array.

Something like


//Lists the contents of the players inventory
Buy.ListPlayerInventory();
 

Consider abstrqcting your classes a little more. The buy class, which i think you intend to be some sort of portal with which the player interacts to purchase items, would not hold the inventory of the player, but would instead only add or remove from it. A design solution might be this:


//holds items
class Inventory;

//has an inventory
class Player;

//holds items for sale
//interacts with the Inventory class that it gets from the player.
class Buy;
 

This way you do not need to be creating memory, but need only create objects and pass by reference.

Thank you both for the great advice. Would it be easier to store the players inventory in a multidimensional array in order to store the objects name and price?

Cpl Alt, Travis A

USMC

Thank you both for the great advice. Would it be easier to store the players inventory in a multidimensional array in order to store the objects name and price?

It depends on how you want to represent the items that would be in the inventory, but that sounds a little over-engineered to me. What you are describing would work, but I would prefer either a Dictionary with a string key and an int value or a distinct Item class with a string field for the name and an int field for the price.

I can flesh this out a bit more, but later; my phone limits my post quality :/

EDIT: Home now, let me expand a little.

I think that creating an Item class would be a good, intuitive, direct approach to take. That way all of the information relevant to the items in your program are grouped together to be conveniently used as you need.

If you had something like:


public class Item
{
string name;
 
int price;

}

then you could have a List<Item> to represent inventory and another List<Item> to represent the store. An array of items (Item[]) would also be fine, though the size would be fixed.

The player's inventory doesn't seem like it would benefit from having item prices, so unless the price is included as a field in an Item class I wouldn't include it in the inventory at all. If you don't use an Item class, I would have the player's inventory be a List<string> or an array of strings, similar to above. The Buy interface is the only place that really needs the prices, so you could use a Dictionary<string, int> where the string is the item name and the int is the price as a field in the Buy class definition.

-------R.I.P.-------

Selective Quote

~Too Late - Too Soon~

If I were to use a Dictionary to set the item and price, then store what the user selects into a List, would I be able to reference the item back to the Dictionary if the user wants to sell that item back for what he paid?

Cpl Alt, Travis A

USMC

Guesswork here, is it because you're creating a new object each time you generate the list?

public void GenerateList()

{ Buy buy = new Buy(); //this 'buy' object is empty

Console.Clear();

Sorry, Khaiy just said the same thing! (Great minds think alike, though fools seldom differ.)

If I were to use a Dictionary to set the item and price, then store what the user selects into a List, would I be able to reference the item back to the Dictionary if the user wants to sell that item back for what he paid?


I'm imagining the dictionary as a persistent variable that is referenced as needed for buying and selling, and inventory is stored separately. So the Buy interface doesn't add or remove an item from the dictionary but only accesses it to get the price for that item. Inventories, like a store's current stock, would be something different (potentially another dictionary with the item as a key and the number in stock as the value, or any other arrangement you like).

If the item/price dictionary variable is named priceList, the Buy interface would get the price for itemX by accessing priceList[itemX].

When the player buys an item, you deduct int price = priceList[itemX] from their current money supply and add the item to their inventory (player.Inventory.Add(the item), if the inventory is a list). To sell the item back, the player's money supply is credited with priceList[itemX] dollars, and the item is removed from the player's inventory (player.Inventory.Remove(the item)).

Does that help? I'm back on my phone, so again my post quality is taking a hit.

EDIT: Home again. Here's a quick sample of what the code might look like if you have a dictionary for storing price information, a list for inventory, a dictionary for store stock, and items represented only as strings:

 
// A class defining a player:
 
public partial class Player
{
     // Fields
     public List<string> inventory;
 
     int money;
}
 
// A class defining a store
 
public partial class Store
{
     // Fields
     public Dictionary<string, int> priceList;
 
     public Dictionary<string, int> itemStock;
 
     // Methods
     public void DisplayStock()
     {
          // Code to display the items for sale
          foreach (string s in itemStock.Keys)
          {
               Console.WriteLine("{0} costs ${1}.", s, priceList[s]);
          }          
     }
 
     public void BuyItem(Player p, string itemPurchased)
     {
          if (p.money >= priceList[itemPurchased])
          {
               p.money -= priceList[itemPurchased];
               p.inventory.Add(itemPurchased);
               itemStock[itemPurchased]--;
          }
 
          else
          {
               Console.WriteLine("You don't have enough money.");
          }
     }
 
     public void SellItem(Player p, string itemSold)
     {
          p.inventory.Remove(itemSold);
          p.money += priceList[itemSold];
          itemStock[itemPurchased]++;
     }
}
 

-------R.I.P.-------

Selective Quote

~Too Late - Too Soon~

Thank you so much for the great and invaluable advice Khaiy. Would you mind if I PMed you about some other questions I have?

Cpl Alt, Travis A

USMC

This topic is closed to new replies.

Advertisement