Reputation: 3
I have two classes. First class takes user input as a string. User can choose for example: bananas, apples, grapes and blueberries.
class Choice
{
string fruit;
public void ChooseFruit()
{
Console.WriteLine("Enter [bananas] or [apples] or [grapes] or [bluebarries]");
fruit = Console.ReadLine();
...
}
}
Second class stores a variables for every fruit for examples if its banana (amount = 102.4, price = 12.34, volume = 16.3) different variables for every fruit.
How to return all the variables (amount, price, volume) to the first class for a chosen fruit in a proper way ?
[EDIT] I tried something like this (it works but it doesnt look right):
class Choice
{
string fruitName;
float amount, price, volume;
public void ChooseFruit()
{
Console.WriteLine("Enter [bananas] or [apples] or [grapes] or [bluebarries]");
string fruitName = Console.ReadLine();
Fruit f1 = new Fruit(fruitName);
amount = f1.Amount;
price = f1.Price;
volume = f1.Volume;
//...................//
}
}
class Fruit
{
public float Amount { get; private set; }
public float Volume { get; private set; }
public float Price { get; private set; }
public Fruit(string name)
{
if (name.ToLower() == "bananas")
{
Amount = 12;
Volume = 1.6f;
Price = 27;
}
else if (name.ToLower() == "grapes")
{
Amount = 12;
Volume = 1.6f;
Price = 27;
}
// AND OTHERS //
}
}
Upvotes: 0
Views: 139
Reputation: 290
It appears that you want the community to solve your school assignments?
Anyway - try and have a look at
or even better
.. and see if you can make sense of it.
Good luck /Anders
Upvotes: 0
Reputation: 1004
Here's a quick implementation:
public enum Fruits {
Bananas,
Apples,
Grapes,
Blueberries
}
public class FruitInfo
{
public Fruits Fruit { get; }
public decimal Price {get; set}
...
}
// TODO: Populate this dictionary with all your fruit info
private Dictionary<Fruits , FruitInfo> _fruitDatabase;
public FruitInfo ChooseFruit()
{
while(true)
{
Console.WriteLine("Choose [bananas], [apples], [grapes], or [blueberries]: ");
var input = Console.ReadLine();
Fruits selection;
if(!Enum<Fruits>.TryParse(input, true, out selection))
{
Console.Error.WriteLine("Invalid Fruit Selection, Try Again.");
continue;
}
return _fruitDatabase[selection];
}
}
Upvotes: 1