Processing int to name of list - c#

I try to write a simple console application with Hanoi towers. But I am stuck at one point.
In my program I ask a person to write from to which tower wants to put the disk, but: I have 3 lists as towers, I'll ask for a number from gamer and now how I can build a "compare method"? Because I don't want to copy the same piece of code 6 times...
class Towers : Disks
{
//public Towers(int Value, int WhereItIs) : base(Value, WhereItIs) { }
public List<Disks> Tower1 = new List<Disks>();
public List<Disks> Tower2 = new List<Disks>();
public List<Disks> Tower3 = new List<Disks>();
public void Compare(int dyskFrom, int dyskWhere) {
}
public void Display() {
foreach(var i in Tower1){
Console.WriteLine("Where: {0} | Value: {1}", i.WhereItIs, i.Value);
}
}
public void Build(int TowerHigh) {
for (int i = TowerHigh; i > 0; i--) {
Tower1.Add(new Disks {Value = i, WhereItIs = 1 });
}
}
}
class Disks
{
public int Value; //wartosc krazka
public int WhereItIs; //na ktorej wiezy sie on znajduje
}
class Program
{
static void Main(string[] args)
{
Towers Tower = new Towers();
int TowerHigh;
Console.Write("Podaj wysokość wieży: ");
TowerHigh = int.Parse(Console.ReadLine());
Tower.Build(TowerHigh);
Tower.Display();
Tower.Compare(1, 2);
}
}

It's easier to create an array of Stack<Disk>(). This way you can select a tower by index.
I would use a Stack, because thats typically the functionality you need.
Something like: PSEUDO (typed in browser, no syntax checked)
class Disk
{
public int Size {get; set;}
}
static void Main(string[] args)
{
// create the Stack<Disk> array
Stack<Disk>[] towers = new Stack<Disk>[3];
// create each tower
for(int i=0;i<towers.Length;i++)
{
towers[i] = new Stack<Disk>();
// fill the towers.
for(int j=3;j>0;j--)
towers[i].Enqueue(new Disk { Size = j });
}
bool isHoldingDisk = false;
while(true)
{
DisplayTowers(towers);
if(isHoldingDisk)
Console.WriteLine("On what tower do you want to place it?");
else
Console.WriteLine("Choose a tower to pick a disk");
var key = Console.ReadKey(true);
var chosenTowerIndex = 0;
switch(key)
{
case(Key.Escape):
break;
case(Key.D1):
chosenTowerIndex = 0;
break;
case(Key.D1):
chosenTowerIndex = 1;
break;
case(Key.D1):
chosenTowerIndex = 2;
break;
// etc...
}
if((chosenTowerIndex < 1) || (chosenTowerIndex >= towers.Length))
continue;
// check here if you are holding a disk
if(isHoldingDisk)
{
// logic for testing if you can place the disk here...
// using towers[chosenTowerIndex]
// check if it is completed...
if(completed)
break;
isHoldingDisk = false;
}
else
{
// check if you can pickup a disk....(if there is any)
isHoldingDisk = true;
}
}
// final display...
DisplayTowers(towers);
Console.WriteLine("Thanks for playing");
}
static void DisplayTowers(Stack<Disk>[] towers)
{
// draw some fancy asc-ii art...
}

Related

Need to change values in classes without changing its reference

I am currently making an application which tracks information on players and monsters for a tabletop game.
Currently I've got classes for "Monsters". This class contains information such as its name, maxHP, speed, attacks etc. I've managed to make a Database which contains the default values for each type of monster. What I currently need to do is make it possible to change things such as name (Monster > Monster 1, Monster 2 etc), change its HP, and some other things.
I understand that I need to make a copy of such, but I am uncertain on how to do this.
What I currently tried is the following:
public class DatabaseService
{
public List<Player> Players { get; set; }
public List<Monster> AllMonsters { get; set; }
public List<Monster> ActiveMonsters = new List<Monster>();
public bool RollForHP = false;
//Main Database Service
public DatabaseService()
{
Players = GetPlayers();
AllMonsters = GetAllMonsters();
}
public void DoStuff()
{
AddMonsterByName("Goblin", 2);
AddMonsterByName("Adult White Dragon", 1);
AddMonsterByName("Duergar", 4);
foreach (Monster monster in ActiveMonsters) { Console.WriteLine(monster.Name); }
}
//Converts the .json list with all players to Classes, which are then stored in the list "Players" if the "IsInParty" is true
private List<Player> GetPlayers()
{
var path = #"C:\Users\MyName\source\repos\DndAdvancedInitiativeTracker\Logic\Database\Players.json";
var json = File.ReadAllText(path);
var players = JsonConvert.DeserializeObject<List<Player>>(json);
List<Player> inPartyPlayers = new List<Player>();
foreach (var player in players)
{
if (player.IsInParty == true) { inPartyPlayers.Add(player); }
}
return inPartyPlayers;
}
//Converts the .json list with all monsters to Classes, which are then stored in the list "AllMonsters"
private List<Monster> GetAllMonsters()
{
var path = #"C:\Users\MyName\source\repos\DndAdvancedInitiativeTracker\Logic\Database\Monsters.json";
var json = File.ReadAllText(path);
var monsters = JsonConvert.DeserializeObject<List<Monster>>(json);
return monsters;
}
//Adds a given monster to the "ActiveMonsters" list
public void AddMonsterByName(string monsterName, int amountOfMonsters)
{
for (int i = 0; i < amountOfMonsters; i++)
{
List<Monster> DatabaseCopy = AllMonsters.Clone();
DatabaseCopy = AllMonsters;
Monster monster = DatabaseCopy.Find(x => x.Name == monsterName);
Console.WriteLine(monster.Name);
var number = CheckIfNameExistsInList(monsterName);
monster.Name = monsterName + " " + (number + i).ToString();
ActiveMonsters.Add(monster);
}
}
private int CheckIfNameExistsInList(string monsterName)
{
var counter = 1;
foreach (var monster in ActiveMonsters)
{
if (monster.Name.Contains(monsterName))
{
counter += 1;
}
}
return counter;
}
}
In the "DoStuff" Method, I try to add 2 goblins, then a dragon, then a goblin again. The first goblin is named to "Goblin 1" correctly, but the second loop fails, because the AllMonsters' name for goblins is now "Goblin 1" because of the reference type, therefore, the second "Goblin" search in AllMonsters is never found, and returns null.
I'm not sure why you're copying your database (and doing so for every iteration of a for loop which is quite wasteful), but your current check code CheckIfNameExistsInList will always return 1 even if there are no matches in the list.
You can simplify your AddMonstersByName (and use a simple check for previous monster entries) as follows:
public void AddMonstersByName(string name, uint number = 1)
{
var count = AllMonsters.Count(x => x.Name.Contains(name));
for (var i = 1; i <= number; i++)
{
var num = count + i;
AllMonsters.Add(new Monster(){Name= name+num.ToString()});
}
}
This was tested in a simple Console App:
var dataService = new DataService();
dataService.AddMonstersByName("Goblin", 2);
dataService.AddMonstersByName("Dragon", 2);
dataService.AddMonstersByName("Goblin", 2);
foreach (var monster in dataService.AllMonsters)
{
Console.WriteLine($"{monster.Name}");
}
where
public class DataService
{
public List<Monster> AllMonsters = new List<Monster>();
public void AddMonstersByName(string name, uint number = 1)
{
var count = AllMonsters.Count(x => x.Name.Contains(name));
for (var i = 1; i <= number; i++)
{
var num = count + i;
AllMonsters.Add(new Monster(){Name= name+num.ToString()});
}
}
}
public class Monster
{
public string Name { get; set; }
}

Display win and loss for a little game

I am trying to make each player display "Each Players Wins and loose at every count, so they can see the ones they won and lost
some thing like:
Player A
Games: Status of Game
1 : Win
2 : Win
3 : Win
4 : Lost
5 : Lost
6 : Win
Player B
Games: Status
1 : Lost
2 : Lost
3 : Lost
4 : Win
5 : Win
6 : Lost
Please help me out with this
class Guess
{
public int GuessedNumber { get; set; }
List<int> PlayerA = new List<int>();
List<int> PlayerB = new List<int>();
int countA = 0;
int countB = 0;
int count = 0;
public void Guu()
{
Random rand = new Random();
GuessedNumber = rand.Next(1,7);
}
public int input { get; set; }
public void FirstDisplay(string Active_Player)
{
Console.WriteLine($"{Active_Player}: Guess the number that i am thinking about");
input = Convert.ToInt32(Console.ReadLine());
count++;
}
public void CompareNumbers(List<int> PlayerA, List<int> PlayerB, ref string Active_Player)
{
if (Active_Player == "A")
{
if (input == GuessedNumber)
{
Console.WriteLine($"Correct, i was thinking of {GuessedNumber} my turn");
PlayerA.Add(1);
PlayerB.Add(0);
countA++;
}
else
{
Console.WriteLine($"Wrong, i was thinking of {GuessedNumber} try again");
PlayerB.Add(1);
PlayerA.Add(0);
countB++;
}
}
else if (Active_Player == "B")
{
if (input == GuessedNumber)
{
Console.WriteLine($"Correct, i was thinking of {GuessedNumber} try again");
PlayerA.Add(0);
PlayerB.Add(1);
countB++;
}
else
{
Console.WriteLine($"Wrong, i was thinking of {GuessedNumber} try again");
PlayerB.Add(0);
PlayerA.Add(1);
countA++;
}
}
}
public void Display()
{
Console.WriteLine("This is the result of the game");
Console.WriteLine($"Number of Game Played is: {count++}");
if (countA > countB)
{
Console.WriteLine("Winner: A");
}
else if (countA < countB)
{
Console.WriteLine("Winner: B");
}
else
{
Console.WriteLine("Draw");
}
Console.WriteLine($"Player A has {countA++} point");
Console.WriteLine($"Player B has {countB++} point ");
}
}
class Program
{
static void Main(string[] args)
{
List<int> PlayerA = new List<int>();
List<int> PlayerB = new List<int>();
string Active_Player = "A";
int count = 0;
Guess guess = new Guess();
string choice;
do
{
guess.Guu();
guess.FirstDisplay(Active_Player);
guess.CompareNumbers( PlayerA, PlayerB, ref Active_Player);
count++;
Console.WriteLine("Do you want to continue, Yes or No?");
choice = Console.ReadLine().ToLower();
}
while(choice == "yes");
guess.Display();
}
}
}
Can't you use List<int> PlayerA and List<int> PlayerB ?
Console.WriteLine("PlayerA Games Status");
for ( int i = 0; i < PlayerA.Count; ++i )
{
Console.Write( $"{i}: " );
if ( PlayerA[i] == 0) Console.WriteLine( "Loss" );
else Console.WriteLine( "Win" );
}
Do the same for PlayerB.

Do different things on each iteration of a loop c#

I am making a game for children on the Sifteo Cubes. I am trying to load a sentence on the cubes, word by word. I have some experience with the Sifteo Cubes but how can I solve this in a more beautiful way? More generic if that's possible.
foreach (CubeWrapper wrapper in mWrappers) {
if (i == 0) {
wrapper.setWord (w1);
} else if (i == 1) {
wrapper.setWord (w2);
} else if (i == 2) {
wrapper.setWord (w3);
} else if (i == 3) {
wrapper.setWord (w4);
} else if (i == 4) {
wrapper.setWord (w5);
}
i++;
}
I will always add w1 to the first wrapper and so on.
Any help would be appreciated!
You can do the following:
String[] words = new String[] {w1,w2,w3,w4,w5};
foreach (CubeWrapper wrapper in mWrappers)
{
wrapper.setWord(words[i++]);
}
This solution is working, but keep in mind, if the words array is smaller than the mWrappers collection you will receive a IndexOutOfBoundsException. So syncing the access to the array is now your work.
If you can't\don't want to change your class then you could use reflection to do something like this (Even though it's probably not the right thing to do here):
foreach (CubeWrapper wrapper in mWrappers) {
var name = "w" + (i+1).ToString();
var value = this.GetType().GetProperty(name).GetValue(this);
wrapper.setWord(value);
}
Example:
public class ABC
{
public int w1 { get; set; }
public int w2 { get; set; }
public int w3 { get; set; }
public ABC()
{
w1 = 7;
w2 = 8;
w3 = 9;
}
public void DoSomething()
{
var i = 1;
var name = "w" + (i + 1).ToString(); // w2
var value = (int)this.GetType().GetProperty(name).GetValue(this);
DoSomething(value);
}
public void DoSomething(int curr)
{
Console.WriteLine(curr); // 8
}
}
Usage:
ABC abc = new ABC();
abc.DoSomething();
You can get a random word from the array, using Random class like this...
String[] words = new String[] { "w1", "w2", "w3", "w4", "w5" };
Random r = new Random(0);
int randomNumber = r.Next(0, words.Length);
foreach (CubeWrapper wrapper in mWrappers)
{
wrapper.setWord(words[randomNumber]);
}

Logic to prevent insertion if there are no available slots

I'm developing an application in ASP.NET with C# and I'm trying to figure out the best way to implement a logic statement that will stop the system from allowing another reservation to be taken if the trailer for canoes and kayaks is full. The issue is the trailer will hold canoes and kayaks, but there's a lot of different combinations.
There are 5 "rows" on the trailer that count upwards vertically, and 2 "columns" that dissect the 5 rows in the middle. I will draw you a diagram to show you what it looks like, and what boats can go where. "C" will stand for Canoe and "K" will stand for Kayak. The trailer looks like this:
C only|C only }
______|______ } BOAT TRAILER
1C\2K|1C\2K }
______|______ }
1C\2K|1C\2K }
______|______ }
1C\2K|1C\2K }
______|______ }
C only| C only }
______|______ }
So my question is, what's the best option as far as coding and logic is concerned to not take any more "reservations" when the trailer is full? This application will be a .aspx form that will do an insert command to SQL server taking customer information.
public enum BoatType : int
{
Kayak = 1,
Canoe = 2
}
public class BoatReservation
{
public int ReservationID { get; set; }
public BoatType ReservationBoatType { get; set; }
}
public class BoatTrailer
{
public List<BoatReservation> CanoeSlots = new List<BoatReservation>();
public List<BoatReservation> RegularSlots = new List<BoatReservation>();
public BoatTrailer()
{
}
public bool AddBoat(BoatReservation b)
{
bool boatAdded = false;
switch (b.ReservationBoatType)
{
case BoatType.Canoe:
if (CanoeSlots.Count() < 4)
{
CanoeSlots.Add(b);
boatAdded = true;
}
else
{
var reg = RegularSlots.Sum(x => Convert.ToInt16(x.ReservationBoatType));
if (reg <= 10)
{
RegularSlots.Add(b);
boatAdded = true;
}
}
break;
case BoatType.Kayak:
{
var reg = RegularSlots.Sum(x => Convert.ToInt16(x.ReservationBoatType));
if (reg <= 11)
{
RegularSlots.Add(b);
boatAdded = true;
}
}
break;
}
return boatAdded;
}
public void RemoveBoat(BoatReservation b)
{
switch (b.ReservationBoatType)
{
case BoatType.Kayak:
if (RegularSlots.Contains(b))
{
RegularSlots.Remove(b);
}
break;
case BoatType.Canoe:
if (RegularSlots.Contains(b))
{
RegularSlots.Remove(b);
}
else
{
if (CanoeSlots.Contains(b))
{
CanoeSlots.Remove(b);
if (RegularSlots.Where(fb => fb.ReservationBoatType == BoatType.Canoe).Count() > 0)
{
//Move Reservation From Regular to Canoe Only With Opening
BoatReservation mv = RegularSlots.FindLast(fb => fb.ReservationBoatType == BoatType.Canoe);
RegularSlots.Remove(mv);
CanoeSlots.Add(mv);
}
}
}
break;
}
}
public string AvailableSlots()
{
string Output = string.Empty;
int AvailableCanoeCnt = (4 - CanoeSlots.Count()) + ((12 - RegularSlots.Count()) / 2);
int AvailableKayakCnt = (12 - RegularSlots.Count());
Output = string.Format("Canoe Slots Left: {0} Kayak Slots Left {1} ", AvailableCanoeCnt, AvailableKayakCnt);
return Output;
}
}
Quick class that handles reservations (both adding and deleting) of canoes/kayaks to fit a trailer.
Not the best question for this site but I will provide a pseudo structure for this.
Trailer Object
JustCanoes int
CanoeKayakBlend int
When reserving...
If the reservation is for a canoe, and the JustCanoes value is < 4, then increase JustCanoes by 1
If JustCanoes is >= 4
If CanoeKayakBlend <= 10
increase CanoeKayakBlend by 2
else
Sorry no reservation available
If the reservation is for a kayak
If CanoeKayakBlend <= 11
increase CanoeKayakBlend by 1
else
Sorry no reservation available
A very quick and simplistic implementation: Here's the Compartment class
class Compartment
{
private readonly int _maxCanoe;
private readonly int _maxKayak;
private int _currentCanoe;
private int _currentKayak;
private readonly int _id;
private bool _fullCanoe;
private bool _fullKayak;
public Compartment(int id, int maxC, int maxK)
{
_id = id;
_maxCanoe = maxC;
_maxKayak = maxK;
_currentCanoe = _currentKayak = 0;
UpdateCapacityStatus();
}
private void UpdateCapacityStatus()
{
_fullCanoe = _maxCanoe == _currentCanoe;
_fullKayak = _maxKayak == _currentKayak;
}
private string Status
{
get { return IsFull() ? "FULL" : "Space available"; }
}
public bool IsFull()
{
return _fullKayak && _fullCanoe;
}
public void AddCanoe()
{
_fullKayak = true; // disable adding kayak
_currentCanoe = _currentCanoe + 1;
_fullCanoe = _maxCanoe == _currentCanoe; //update canoe status
}
public void AddKayak()
{
_fullCanoe = true; //disable adding canoe
_currentKayak = _currentKayak + 1;
_fullKayak = _maxKayak == _currentKayak; //update kayak status
}
public override string ToString()
{
return string.Format("Id: {5}, Status: {0}, with {1} of {2} canoes or {3} of {4} kayaks", Status, _currentCanoe, _maxCanoe, _currentKayak, _maxKayak, _id);
}
public bool CanAddCanoe()
{
return !_fullCanoe;
}
public bool CanAddKayak()
{
return !_fullKayak;
}
}
And here's the driver console app to test, to use it you should refactor it of course.
`class Program
{
static void Main(string[] args)
{
var trailer = new List
{
new Compartment(1, 1, 0),
new Compartment(2, 1, 0),
new Compartment(3, 1, 2),
new Compartment(4, 1, 2),
new Compartment(5, 1, 2),
new Compartment(6, 1, 2),
new Compartment(7, 1, 2),
new Compartment(8, 1, 2),
};
foreach (var compartment in trailer)
{
Console.WriteLine(compartment.ToString());
}
Console.WriteLine("Press c for canoe or k for kayak");
var keepGoing = true;
while (keepGoing)
{
var input = Console.Read();
if (input == 99 || input == 107) //99 c, 107 k
{
if (trailer.All(c => c.IsFull()))
{
keepGoing = false;
}
else
{
if (input == 99)
{
if(!trailer.Any(t=>t.CanAddCanoe()))
{
Console.WriteLine("Cannot add a canoe!!!!");
}
else
{
var firstAvailable = trailer.First(c => c.CanAddCanoe());
firstAvailable.AddCanoe();
}
}
else if (input == 107)
{
if (!trailer.Any(t => t.CanAddKayak()))
{
Console.WriteLine("Cannot add a kayak!!!!");
}
else
{
var firstAvailable = trailer.First(c => c.CanAddKayak());
firstAvailable.AddKayak();
}
}
else
{
Console.WriteLine("Press c for canoe or k for kayak");
}
}
foreach (var compartment in trailer)
{
Console.WriteLine(compartment.ToString());
}
}
}
Console.ReadKey();
}
}`

I need a simple and elegant user validation technique for a c# console application

Coming from a procedural background, I'm running into a conceptual block while designing a menu-based console application and user input validation. My goal is to display a menu that launches other processes. I want to limit user input to 1, 2, or 3 at the menu.
In a procedural language, I would do something like this pseudocode:
10 print "Make a choice"
20 choice = [dataFromKeyboard]
30 if choice < 4 && choice > 0
40 then 10
50 else 60
60 process valid choices
and no matter what I try, I can't get that out of my head while designing an OO program. Consider (simplified to include only 3 menu items):
class Menu
{
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
int menuChoice = thisdm.displayMenu();
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
}
}
class DisplayMenu
{
public int displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
return intChoice;
}
}
class ProcessMenu
{
public void processMenu(int choice)
{
switch(choice)
{
case 1:
foo1();
break;
case 2:
foo2();
break;
case 3:
foo3();;
break;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
}
So here's where I'm stuck. I just can't wrap my head around a simple and elegant way validate my user input that's from an OO rather than procedural standpoint.
Assuming I do the validation in the DisplayMenu, I would be validating after the input is read. But if it turns out to be invalid, how do I re-ask for valid input, since I've already called displayMenu method from Main?
I've been playing with while loops for about an hour, something like this:
intChoice = 0;
[print the menu]
while ((intChoice<1) || (intChoice>3))
Console.WriteLine("Please make a valid choice from the menu");
choice = Console.ReadLine();
etc.
but can't seem to find the sweet spot where I can control user input.
I suspect it's because I'm thinking to procedurally, and not object-oriented enough. Anyone have any tips or input to help me wrap my head around this?
Expanding on #AlexeiLevenkov's suggestion of "turning your classes 90 degrees", I went a step further and created this example of a "Modular" console Application:
class Program
{
static void Main(string[] args)
{
//Retrieve all Module types in the current Assembly.
var moduletypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsSubclassOf(typeof(ConsoleModule)));
//Create an instance of each module
var modules = moduletypes.Select(Activator.CreateInstance)
.OfType<ConsoleModule>()
.OrderBy(x => x.Id)
.ToList();
int SelectedOption = -1;
while (SelectedOption != 0)
{
//Show Main Menu
Console.Clear();
Console.WriteLine("Please Select An Option:\n");
modules.ForEach(x => Console.WriteLine(string.Format("{0} - {1}", x.Id, x.DisplayName)));
Console.WriteLine("0 - Exit\n");
int.TryParse(Console.ReadLine(), out SelectedOption);
//Find Module by Id based on user input
var module = modules.FirstOrDefault(x => x.Id == SelectedOption);
if (module != null)
{
//Execute Module
Console.Clear();
module.Execute();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
}
}
ConsoleModule class:
public abstract class ConsoleModule
{
public int Id { get; set; }
public string DisplayName { get; set; }
public abstract void Execute();
}
Some sample Modules:
public class EnterUserNameModule : ConsoleModule
{
public EnterUserNameModule()
{
Id = 2;
DisplayName = "User Name";
}
public static string UserName { get; set; }
public override void Execute()
{
Console.WriteLine("Please Enter Your Name: ");
UserName = Console.ReadLine();
}
}
public class HelloWorldModule: ConsoleModule
{
public HelloWorldModule()
{
Id = 1;
DisplayName = "Hello, World!";
}
public override void Execute()
{
Console.WriteLine("Hello, " + (EnterUserNameModule.UserName ?? "World") + "!");
}
}
public class SumModule: ConsoleModule
{
public SumModule()
{
Id = 3;
DisplayName = "Sum";
}
public override void Execute()
{
int number = 0;
Console.Write("Enter A Number: ");
if (int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Your number plus 10 is: " + (number + 10));
else
Console.WriteLine("Could not read your number.");
}
}
Result:
It uses a little bit of reflexion to find all types deriving from ConsoleModule in the current assembly, then shows a menu with all these options (which are actually properties in this class), and calls the Execute() method when an appropiate option is selected. Much more towards OO way of thinking.
Make your processMenu function return some kind of indicator. You could use exceptions for this instead, but that's overkill.
public bool processMenu(int choice)
{
....
}
If the choice was acceptable, then return true, otherwise return false. Then:
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
ProcessMenu thispm = new ProcessMenu();
int menuChoice;
do {
menuChoice = thisdm.displayMenu();
} while( !thispm.processMenu(menuChoice) );
}
The way you are doing should be changed. Anyhow, for the same as your question, this works out:
DisplayMenu thisdm = new DisplayMenu();
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 3)
{
Console.WriteLine("enter valid choice");
menuChoice = thisdm.displayMenu();
}
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
the code like:
class Program
{
static void Main(string[] args)
{
DisplayMenu thisdm = new DisplayMenu();
ProcessMenu thispm = new ProcessMenu();
thisdm.displayMenu();
int menuChoice = thispm.GetChoice();
thispm.processMenu(menuChoice);
Console.Read();
}
}
class DisplayMenu
{
public void displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
}
}
class ProcessMenu
{
public int GetChoice()
{
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
while (!Validate(intChoice))
{
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
choice = Console.ReadLine();
intChoice = Convert.ToInt32(choice);
}
return intChoice;
}
public void processMenu(int choice)
{
switch (choice)
{
case 1:
//foo1();
break;
case 2:
//foo2();
break;
case 3:
//foo3(); ;
break;
default:
//Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
private int[] forChoices=new int[]{1,2,3};
private bool Validate(int choice)
{
if(forChoices.Contains(choice))
{
return true;
}
return false;
}
}

Categories