Unsure how to handle exception in hot potato game C# - c#

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():

Related

how to stop my code from looping at the end?

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();

Trying to make the answer randomly generated after retry in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int num1 = int.Parse(args[0]);
int num2 = int.Parse(args[1]);
bool GameOver = false;
int turn = 3;
Random random = new Random();
int answer = random.Next(num1, num2);
// string input = "";
Console.WriteLine("Hello, welcome to the guess a number challenge");
while (!GameOver)
{
if (turn != 0)
{
turn--;
Console.WriteLine($"Please Select number between {num1} to {num2}:");
int SelectedNumber = int.Parse(Console.ReadLine());
if (SelectedNumber < answer && SelectedNumber >= num1)
{
System.Console.WriteLine("Almost there, just the number is too small\n");
} else if (SelectedNumber > answer && SelectedNumber <= num2)
{
System.Console.WriteLine("Your number is too big\n");
} else if(SelectedNumber == answer)
{
System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
GameOver = true;
retry();
} else
{
System.Console.WriteLine("Your number is out of range\n");
}
} else
{
System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
GameOver = true;
retry();
}
void retry() {
System.Console.WriteLine("Would you like to retry? Y/N");
string input = Console.ReadLine();
string ConsoleInput = input.ToLower();
if(ConsoleInput == "y")
{
GameOver = false;
turn = 3;
} else if(ConsoleInput == "n")
{
GameOver = true;
} else
{
Console.WriteLine("Invalid input");
retry();
}
}
}
}
}
}
Hello all, just want to ask a question.
I tried to build "guess a number" game in terminal, where player has to guess a number based on the number range given.
I tried to make the answer randomly generated, thus the Random class.
and the answer will be randomized after retry.
The problem is, after each retry, the answer is still the same.
I am not sure where did I did wrong.
Thanks for the help, and sorry for the noob question.
i edited out your code
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter num1");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter num2");
int num2 = int.Parse(Console.ReadLine());
bool GameOver = false;
int turn = 3;
Random random = new Random();
int answer = random.Next(num1, num2);
// string input = "";
Console.WriteLine("Hello, welcome to the guess a number challenge");
while (!GameOver)
{
if (turn != 0)
{
turn--;
Console.WriteLine($"Please Select number between {num1} to {num2}:");
int SelectedNumber = int.Parse(Console.ReadLine());
if (SelectedNumber < answer && SelectedNumber >= num1)
{
System.Console.WriteLine("Almost there, just the number is too small\n");
}
else if (SelectedNumber > answer && SelectedNumber <= num2)
{
System.Console.WriteLine("Your number is too big\n");
}
else if (SelectedNumber == answer)
{
System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
GameOver = true;
retry();
}
else
{
System.Console.WriteLine("Your number is out of range\n");
}
}
else
{
System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
GameOver = true;
retry();
}
void retry()
{
System.Console.WriteLine("Would you like to retry? Y/N");
string input = Console.ReadLine();
string ConsoleInput = input.ToLower();
if (ConsoleInput == "y")
{
answer = random.Next(num1, num2);
GameOver = false;
turn = 3;
}
else if (ConsoleInput == "n")
{
GameOver = true;
}
else
{
Console.WriteLine("Invalid input");
retry();
}
}
}
}
}
}
You need an outside loop in order to start a new game after the end:
See below a skeleton program with the necessary control flow.
class Program
{
static void Main(string[] args)
{
bool retry = false;
do
{
// start of game
bool gameOver = false;
int turn = 3;
do
{
// game here
// set gameOver when guess is corrent
turn--;
} while (turn>0 && !gameOver);
// post game scores
// ask to retry
} while (retry);
// end here
}
}

How do I tell my console app not to continue until i enter a number?

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);

Random Number Guessing Game Answers 0

I am creating a random number guessing game where the user sets the maximum number they want to guess from. I have figured out most of the code, the problem that I seem to be getting is that after setting the maximum number and beginning to guess the answer is always 0. Any tips on how to adjust my code so that the answer is a number within the range and not 0?
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
public static string decision;
static void Main(string[] args)
{
int UserNumber;
SelectedNumber = ran.Next(0, UserMaxValue);
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
public static void GuessNumber(int UserNumber)
{
if (UserNumber < SelectedNumber)
Console.WriteLine("Your number is wrong, please try again!");
else if (UserNumber > SelectedNumber)
Console.WriteLine("Your Number is wrong, please try again!");
//else if (UserNumber == 0)
// Console.WriteLine("Your Number is wrong, please try again!");
else
{
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n) ", decision);
decision = Console.ReadLine();
if (decision == "n")
GameOver = true;
else
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
}
}
}
You have the following lines, in this order (I'm omitting the rest in between):
public static int UserMaxValue = 0;
// ...
SelectedNumber = ran.Next(0, UserMaxValue);
// ...
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
You have to ask the user for UserMaxValue before you can correctly set SelectedNumber.
Had to do some corrections on your code. Added some comments for the changes.
You better add error handling on the user input.
UPDATE: Added error handling for invalid input.
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
static void Main(string[] args)
{
int UserNumber = 0;
bool playAgain = false;
do
{
bool isUserMaxValueValid = false;
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
isUserMaxValueValid = int.TryParse(Console.ReadLine(), out UserMaxValue);
} while (!isUserMaxValueValid);
SelectedNumber = ran.Next(1, UserMaxValue); // Re-assign SelectedNumber for every new max number input. Random number start changed to 1 to avoid 0 value for SelectedNumber
do
{
bool isUserNumberValid = false;
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
isUserNumberValid = int.TryParse(Console.ReadLine(), out UserNumber);
} while (!isUserNumberValid);
playAgain = GuessNumber(UserNumber);
// I changed GameOver to see if the guessing portion is finished or not
} while (!GameOver); // You don't need to use GameOver == false
} while (playAgain); // Check if user wants to play again or not
}
public static bool GuessNumber(int UserNumber)
{
if (UserNumber != SelectedNumber)
{
GameOver = false;
Console.WriteLine("Your number is wrong, please try again!");
}
else
{
GameOver = true;
bool isPlayAgainValid = false;
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n)");
do
{
string decision = Console.ReadLine();
if (decision.Equals("n", StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
else if (decision.Equals("y", StringComparison.InvariantCultureIgnoreCase))
{
break;
}
if(!isPlayAgainValid)
{
Console.WriteLine("Please enter y or n only.");
}
} while (!isPlayAgainValid);
// I removed redundant code
}
return true;
}
}

How to make number Count in loop in c#?

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;
}

Categories

Resources