This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}
Related
i'm new at coding C# pls help me fix this simple dice game, it keeps on looping at the end of the game
** apparently how i think is that in the end of this code something makes the NO commend on looping and getting re runed**
using System;
namespace first_game
{
class Program
{
static void Main(string[] args)
{
string userName;
userName = Console.ReadLine();
#region
{
int userPoint = 0;
int cpuPoint = 0;
int pDice;
bool closeApp;
while (true)
{
while (cpuPoint < 10 && userPoint < 10)
{
Random rd = new Random();
pDice = rd.Next(1, 6);
#endregion
int P2Dice;
Random scondRd = new Random();
P2Dice = scondRd.Next(1, 6);
Console.ReadLine();
Console.WriteLine("-------------------");
Console.Write("playe dice:");
Console.WriteLine(pDice);
Console.Write("CPU dice:");
Console.WriteLine(P2Dice);
Console.ReadLine();
if (pDice > P2Dice)
{
userPoint = userPoint + 1;
}
else if (pDice < P2Dice)
{
cpuPoint = cpuPoint + 1;
}
Console.Clear();
Console.WriteLine(userName);
Console.Write("player point:");
Console.WriteLine(userPoint);
Console.Write("CPU point:");
Console.Write(cpuPoint);
Console.ReadLine();
}
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
Console.ReadLine();
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
Console.ReadLine();
}
Console.WriteLine("wanna continue?\n press Y for yes press N for NO");
ConsoleKeyInfo sw;
sw = Console.ReadKey();
Console.Clear();
if (sw.Key == ConsoleKey.Y)
{
userPoint = 0;
cpuPoint = 0;
continue;
}
else if (sw.Key == ConsoleKey.N)
{
}
else
Console.WriteLine("ERROR!");
}
}
}
}
}
You seem to have the wrong idea about continue. A while loop always (given a true condition) reruns if it reaches the end, a continue just starts the next iteration early.
else if (sw.Key == ConsoleKey.N) { }
else Console.WriteLine("ERROR!");
This is where you should exit the loop, for example using a break
else if (sw.Key == ConsoleKey.N) {
break;
} else Console.WriteLine("ERROR!");
Add a break to exit the while loop:
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
break;
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
break;
}
Then add this after the while loop, so that the console doesn't close:
Console.ReadLine();
I'd like to make the C# console only accept input from the Enter key on the startup screen.
I've made it so that it closes the console when anything but the Enter key is pressed.
How can I make it so that the console only accepts input from the Enter key so that the application doesn't close when I press anything else, and then receive normal input afterwards?
class Program
{
public static void ClearKeyBuffer()
{
while (Console.KeyAvailable)
Console.ReadKey(true);
}
public static void Main (string[] args)
{
int attempts = 0;
int displayattempts = 5;
bool validentry;
Console.WriteLine("Please press enter to begin");
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
while (attempts < 5)
{
string input;
attempts = (attempts + 1);
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
Console.Clear();
Console.WriteLine("Please enter your user number.");
Console.WriteLine("Attempts Remaining:" + displayattempts);
ClearKeyBuffer();
Console.WriteLine(" ");
input = Console.ReadLine();
{
if (input == "5573")
{
validentry = true;
}
else
{
validentry = false;
}
if (validentry == false)
{
displayattempts = (displayattempts - 1);
Console.Clear();
Console.WriteLine("Error: Invalid number ID entered. Please wait 5
seconds, and try again.");
Thread.Sleep(5000);
}
else if (validentry == true)
{
Console.Clear();
Console.WriteLine("Welcome Samuel");
ValidUserEntry();
}
}
}
}
if (displayattempts == 0)
{
Console.Clear();
Console.WriteLine("Error: You have entered the wrong number ID too many times.
This system will now close in 5 seconds...");
Thread.Sleep(5000);
Environment.Exit(0);
}
}
public static void ValidUserEntry()
{
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("What would you like to do?");
Console.ReadLine();
}
}
Add this line before first if. Then remove if statement and the var key... line.
while (Console.ReadKey(true).Key != ConsoleKey.Enter);
Alternative, more verbose version:
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
} while (key.Key != ConsoleKey.Enter);
I am working on a simple code that asks for the name, age, and gender of at most 5 patients. After each patient, it should ask to input another patient or return to main menu. Once 5 have been input into an array, there should be a prompt to the user that the array is full.
My problem is the code asks for name,age and gender 5 times upfront, and does not give any indication the array is full. How would I change the code to reflect that and still save the inputs? (Code below).
class MainClass
{
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
public static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
string selection = "";
Record[] patients = new Record[5];
GetRecords(patients);
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
selection = Console.ReadLine();
switch (selection)
{
case "a":
GetRecords(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
}
}
static void Stats(Record[]patient_rec)
{
}
}
I would suggest trying to make your code a little easier to read - and more robust.
Try this:
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.WriteLine("Record {0} of {1} entry", i + 1, patient_rec.Length);
patient_rec[i] = new Record()
{
_Age = AskInteger("Enter your age: "),
_Name = AskString("Enter your name: "),
_Gender = AskGender("Enter your gender (female or male): "),
};
string ask = "";
while (string.IsNullOrEmpty(ask) || (ask.ToLower()[0] != 'y' && ask.ToLower()[0] != 'n'))
{
Console.WriteLine("Continue? yes or no (then hit enter)");
ask = Console.ReadLine();
}
if (ask.ToLower()[0] == 'y')
{
continue;
}
break;
}
Console.WriteLine("Thank you. Input completed.");
}
To make this work you need these three input functions:
private static int AskInteger(string message)
{
int result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!int.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
private static string AskString(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
while (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return input;
}
private static Gender AskGender(string message)
{
Gender result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!Gender.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
Your loop is only set to go to the size of the array, so logically you could show a message after the loop (this will get hit when the loop finishes).
If you were controlling your array access in a while loop then just compare your indexer i to the length of the array (patient_rec.Length), if it equals or exceeds the length then show the message.
I would do it in a simpler way:
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
IList<Record> patients = GetRecords(5);
SchedulePatients(patients);
}
static void SchedulePatients(IList<Record> patients)
{
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
string selection = Console.ReadLine();
switch (selection)
{
case "a":
patients.Add(GetRecord());
SchedulePatients(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static IList<Record> GetRecords(int amount)
{
IList<Record> patients = new List<Record>();
for (int i = 0; i < amount; i++)
{
patients.Add(GetRecord());
}
return patients;
}
static Record GetRecord()
{
Record patient = new Record();
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient._Age);
Console.Write("Enter your name: ");
patient._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Enum.TryParse(Console.ReadLine(), out patient._Gender);
return patient;
}
static void Stats(IList<Record> patients)
{
foreach (var patient in patients)
{
Console.WriteLine(string.Concat("Name: ", patient._Name, " Age: ", patient._Age, " Gender: ", patient._Gender));
}
Console.ReadLine();
}
}
If you would like to meet the requirements with the smallest change possible, you just need to add the bit about prompting the user.
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
Console.Write("Enter another (Y/N)? ");
var s = Console.ReadLine();
if (s.ToUpper() != "Y") return;
}
Console.WriteLine("You've entered the maximum number of records.");
}
static int beverageSelection()
{
Console.WriteLine();
int brand;
string _val = "";
Console.Write("Enter number: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
brand = Convert.ToInt32(Console.ReadLine());
return brand;
}
The method above is giving me a headache. I cannot figure out how to tell the console app that it shouldn't let me input any character or even the enter button until I have typed a number into the console. Then and only then should I be able to press enter.
In any case this program is a vending machine I created for fun and I do not fully understand the do while loop in this code just to be clear.
Use Console.ReadLine instead of Console.ReadKey:
int brand = 0;
while (true)
{
string val = Console.ReadLine();
if (int.TryParse(val, out brand)) break;
}
Improved your original code to display and accept only numbers
static void Main(string[] args)
{
Console.WriteLine();
int brand;
string _val = "";
Console.Write("Enter number: ");
while(true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && int.TryParse(_val, out brand))
{
Console.WriteLine();
break;
}
if (key.Key != ConsoleKey.Backspace)
{
int val;
if (int.TryParse(key.KeyChar.ToString(), out val))
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (_val.Length > 0)
{
_val = _val.Substring(0, _val.Length - 1);
Console.Write("\b \b");
}
}
}
Console.WriteLine("Brand: {0}", brand);
Console.ReadKey();
}
For the sake of completeness, if anyone wants the console to prevent non-numeric characters until a numeric value is chosen, you can simply use this unerring code to accomplish your task:
int inputBoundary = Console.CursorLeft;
string consoleInput = String.Empty;
ConsoleKeyInfo inputKey;
while((inputKey = Console.ReadKey(true)).Key != ConsoleKey.Enter || consoleInput == String.Empty)
{
if (inputKey.Key == ConsoleKey.Backspace && Console.CursorLeft != inputBoundary)
{
Console.Write("\b \b");
consoleInput = consoleInput.Remove(consoleInput.Length - 1);
continue;
}
if (Char.IsNumber(inputKey.KeyChar))
{
Console.Write(inputKey.KeyChar);
consoleInput += inputKey.KeyChar;
}
}
int selection = Int32.Parse(consoleInput);
I'm making a hot-potato game in C#. In the code I was trying to handle an exception in the Game() method where it will prompt you to pass the potato to someone (by their player number) it would prevent you from entering your own player number (trying to pass it to yourself.)
The only thing is, I'm having trouble trying to handle the exception:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HotPotatoe
{
class Program
{
public static void Main()
{
Console.Clear();
Console.Write("How many players are there? (up to 4): ");
string PlayerCount = Console.ReadLine();
string PlayerOne = null;
string PlayerTwo = null;
string PlayerThree = null;
string PlayerFour = null;
if (PlayerCount == "2")
{
Console.Write("Enter player 1's name: ");
PlayerOne = Console.ReadLine();
Console.Write("Enter player 2's name: ");
PlayerTwo = Console.ReadLine();
Random ran = new Random();
int WhoStarts = ran.Next(1, 2);
Game(PlayerOne, PlayerTwo, PlayerThree, PlayerFour, WhoStarts);
}
else if (PlayerCount == "3")
{
Console.Write("Enter player 1's name: ");
PlayerOne = Console.ReadLine();
Console.Write("Enter player 2's name: ");
PlayerTwo = Console.ReadLine();
Console.Write("Enter player 3's name: ");
PlayerThree = Console.ReadLine();
Random ran = new Random();
int WhoStarts = ran.Next(1, 3);
Game(PlayerOne, PlayerTwo, PlayerThree, PlayerFour, WhoStarts);
}
else if (PlayerCount == "4")
{
Console.Write("Enter player 1's name: ");
PlayerOne = Console.ReadLine();
Console.Write("Enter player 2's name: ");
PlayerTwo = Console.ReadLine();
Console.Write("Enter player 3's name: ");
PlayerThree = Console.ReadLine();
Console.Write("Enter player 4's name: ");
PlayerFour = Console.ReadLine();
Random ran = new Random();
int WhoStarts = ran.Next(1, 4);
Game(PlayerOne,
PlayerTwo,
PlayerThree,
PlayerFour,
WhoStarts);
}
else
{
Console.WriteLine("Not valid!");
Console.ReadKey();
Main();
}
}
private static void Game
(string player1,
string player2,
string player3,
string player4,
int whoStarts)
{
Player Player1 = new Player();
Player Player2 = new Player();
Player Player3 = new Player();
Player Player4 = new Player();
Player1.Name = player1;
Player2.Name = player2;
Player3.Name = player3;
Player4.Name = player4;
Player1.Number = 1;
Player2.Number = 2;
Player3.Number = 3;
Player4.Number = 4;
Player1.IsOut = false;
Player2.IsOut = false;
if(Player3.Name == null)
{
Player3.IsOut = true;
}
else
{
Player3.IsOut = false;
}
if (Player4.Name == null)
{
Player4.IsOut = true;
}
else
{
Player3.IsOut = false;
}
switch (whoStarts)
{
case 1:
Player1.HasPotatoe = true;
break;
case 2:
Player2.HasPotatoe = true;
break;
case 3:
Player3.HasPotatoe = true;
break;
default:
Player4.HasPotatoe = true;
break;
}
List<Player> PlayingList = new List<Player>
{
Player1,
Player2
};
if (Player3.IsOut == false)
{
PlayingList.Add(Player3);
}
if (Player4.IsOut == false)
{
PlayingList.Add(Player4);
}
Random rand = new Random();
int NumOfRounds = rand.Next(1, 10);
do
{
foreach (Player p in PlayingList)
{
if (p.HasPotatoe == true)
{
Console.Write("Player {0} has the potatoe! Who do you want to pass it to? (by number): ", p.Number);
string input = Console.ReadLine();
if (input == "1")
{
PlayingList[0].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "2")
{
PlayingList[1].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "3")
{
if (Player3.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[2].HasPotatoe = true;
NumOfRounds--;
}
}
else if (input == "4")
{
if (Player4.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[3].HasPotatoe = true;
NumOfRounds--;
}
}
else if(input == p.Number.ToString()) // this is the part i'm having trouble with................................
{
Console.WriteLine("{0}", p.Number.ToString());
Console.WriteLine("You can't pass it to yourself! -_- Choose someone else..." + p.Number.ToString());
Console.ReadKey();
}
}
}
} while (NumOfRounds != 0);
if(Player1.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player1.Name);
Console.ReadKey();
Main();
}
else if(Player2.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player2.Name);
Console.ReadKey();
Main();
}
else if (Player3.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player3.Name);
Console.ReadKey();
Main();
}
else if (Player4.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player4.Name);
Console.ReadKey();
Main();
}
}
}
class Player
{
public string Name { get; set; }
public int Number { get; set; }
public bool HasPotatoe { get; set; }
public bool IsOut { get; set; }
}
}
The specific part where the error is:
Random rand = new Random();
int NumOfRounds = rand.Next(1, 10);
do
{
foreach (Player p in PlayingList)
{
if (p.HasPotatoe == true)
{
Console.Write("Player {0} has the potatoe! Who do you want to pass it to? (by number): ", p.Number);
string input = Console.ReadLine();
if (input == "1")
{
PlayingList[0].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "2")
{
PlayingList[1].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "3")
{
if (Player3.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[2].HasPotatoe = true;
NumOfRounds--;
}
}
else if (input == "4")
{
if (Player4.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[3].HasPotatoe = true;
NumOfRounds--;
}
}
else if(input == p.Number.ToString()) // this is where the problem is...
{
Console.WriteLine("{0}", p.Number.ToString());
Console.WriteLine("You can't pass it to yourself! -_- Choose someone else..." + p.Number.ToString());
Console.ReadKey();
}
}
}
} while (NumOfRounds != 0);
so basically I say: if(input == p.Number().ToString()) // p.Number() == player's number
then throw the exception. But i'm not sure how to go about that. I've tried converting the integer to a string with the .ToString() method. but it doesn't seem to change anything. I've also tried turning the input into a 32 bit integer with the Int32.Parse(input) method, but still no luck. The result just does something random. For example if I was player two, and I prompt to pass the potato to player two, then it will just write to the console that player 2 has the potato over and over. I'm not sure how to do this right. Any suggestions?
throw an exception is simple.
else if(input == p.Number.ToString())
throw new Exception("You cant do that");
Maybe your issue is creating your own exceptions to catch them later. Do
public class BadPlayerException: Exception
{
}
...
throw new BadPlayerEcxeption():