Program ending in the middle of being ran [closed] - c#

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 2 years ago.
Improve this question
using System;
using System.Collections.Generic;
namespace Learning_C__Program
{
class Program
{
static void Main(string[] args)
{
int enemyHealth = 1000;
int playerHealth = 1000;
string[] limbPicked = {"","","",""};
string[] enemyTypes = {"Ogre","Beast","Dragon"};
Random enemyPick = new Random();
int pickEnemy = enemyPick.Next(2);
// Below is the if statements for when an ogre is picked
int i = 1;
while(i == 1) {
if (pickEnemy == 0||pickEnemy == 1||pickEnemy == 2) {
string enemyUsing;
if (pickEnemy == 0) {
enemyUsing = enemyTypes[0];
}
else if (pickEnemy == 1) {
enemyUsing = enemyTypes[1];
}
else {
enemyUsing = enemyTypes[2];
}
Console.WriteLine("You encounter an unhappy " + enemyUsing + "! It starts a fight!\nSelect a limb to hit: ");
limbPicked[0] = Convert.ToString(Console.ReadLine());
if (limbPicked[0] == "Head"||limbPicked[0] == "head"||limbPicked[0] == "Torso"||limbPicked[0] == "torso"||limbPicked[0] == "Arms"||limbPicked[0] == "arms"||limbPicked[0] == "Legs"||limbPicked[0] == "legs") {
Random hitAmount = new Random();
int damage1 = hitAmount.Next(1,300);
Console.WriteLine("You attempted to strike the " + enemyUsing + " in the " + limbPicked[0] + " doing " + damage1 + " damage to the " + enemyUsing + "! They now have " + (enemyHealth - damage1) + " health!");
enemyHealth = enemyHealth - damage1;
Random enemyHitAmount = new Random();
int damage2 = enemyHitAmount.Next(1,300);
Console.WriteLine("The enemy attacks! They do " + damage2 + " damage to you! You now have " + (playerHealth - damage2) + " health!");
playerHealth = playerHealth - damage2;
if (playerHealth == 0) {
Random deathSentence = new Random();
int words = deathSentence.Next(7);
string[] wordsSaying = {"slain","slaughtered","murdered","defeated","beheaded","impaled","shredded"};
if (words == 0) {
Console.WriteLine("The enemy has slain you\nPress any key to exit");
}
else if (words == 1) {
Console.WriteLine("The enemy has slaughtered you\nPress any key to exit");
}
else if (words == 2) {
Console.WriteLine("The enemy has murdered you\nPress any key to exit");
}
else if (words == 3) {
Console.WriteLine("The enemy has defeated you\nPress any key to exit");
}
else if (words == 4) {
Console.WriteLine("The enemy has beheaded you\nPress any key to exit");
}
else if (words == 5) {
Console.WriteLine("The enemy has impaled you\nPress any key to exit");
}
else {
Console.WriteLine("The enemy has shredded you\nPress any key to exit");
}
Console.ReadKey();
if (enemyHealth == 0) {
Random deathSentence2 = new Random();
int words2 = deathSentence2.Next(7);
string[] wordsSaying2 = {"slain","slaughtered","murdered","defeated","beheaded","impaled","shredded"};
if (words2 == 0) {
Console.WriteLine("You have slain the enemy\nPress any key to exit");
}
else if (words2 == 1) {
Console.WriteLine("You have slaughtered the enemy\nPress any key to exit");
}
else if (words2 == 2) {
Console.WriteLine("You have murdered the enemy\nPress any key to exit");
}
else if (words2 == 3) {
Console.WriteLine("You have defeated the enemy\nPress any key to exit");
}
else if (words2 == 4) {
Console.WriteLine("You have beheaded the enemy\nPress any key to exit");
}
else if (words2 == 5) {
Console.WriteLine("You have impaled the enemy\nPress any key to exit");
}
else {
Console.WriteLine("You have shredded the enemy\nPress any key to exit");
}
Console.ReadKey();
}
}
else {
Console.WriteLine("That is not one of the available limbs, please select one of the following:\nHead\nTorso\nArms\nLegs");
}
}
break;
}
Console.ReadKey();
}
}
}
}
My code is starting, and then when I go to input the area I want to try to hit, it moves on to line 48, where it starts to print out "You attempted to strike the " + enemyUsing + " in the " etc
But it types Y then ends for some reason! Please help!

just remove break; at line 150, which exits the while (i == 1) loop
Also looks like you misplaced else block, it should be after checking user input, not after if (playerHealth == 0)
else
{
Console.WriteLine("That is not one of the available limbs, please select one of the following:\nHead\nTorso\nArms\nLegs");
}
The location of the break; actually should be after one of your exit conditions
else
{
Console.WriteLine("You have shredded the enemy\nPress any key to exit");
}
Console.ReadKey();
break; // exit while loop or return; if you want to stop game

Related

Error detected trying to receive input as an integer in C#

I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = int.Parse(Console.ReadLine());
score += add;
if (input == 18)
{
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
break;
}
else if (input > 25)
{
Console.WriteLine("Error.");
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:
static void Main(string[] args)
{
int number;
string input;
bool guessed = false;
int score = 0;
while (!guessed)
{
Console.Write("Guess A Number Between 1 and 25: ");
input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if(number>=1 && number<=25)
{
score++;
if (number == 18)
{
guessed = true;
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
else
{
Console.WriteLine("Number must be between 1 and 25!");
}
}
else
{
Console.WriteLine("That's not a number!");
}
Console.WriteLine();
}
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}

my if/else if statment makes me input multiple times before running

So when I run the code I can press 1 and that runs fine but when I try entering 2 or 3 then the computer makes me enter 2 or 3 multiple times before running that line of code.
I don't know what the problem with this is.
I'm new so if there is a better way to run something like this instead of if statements please let me know.
using System;
namespace PracticeScript
{
class Program
{
static void Main()
{
Random rnd = new Random();
int playerHp = 100;
int enemyHp = 100;
int playerD = rnd.Next(10, 15);
int enemyD = rnd.Next(10, 15);
int potion = 25;
Console.Write("Get Ready! It's time to battle! ");
Console.WriteLine("You stare into the eyes of the ugly goblin and are ready to slay it with your sword \n");
do
{
Console.WriteLine(" what will you do now?");
Console.WriteLine("\n 1. Attack 2. Defend 3. Use potion");
if (Console.ReadLine() == "1")
{
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
}
else if (Console.ReadLine() == "2")
{
Console.WriteLine("You prepaired your sheild for the incoming attack");
}
else if (Console.ReadLine() == "3")
{
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!" );
}
Console.WriteLine("\nEnemy Turn!");
playerHp -= enemyD;
Console.WriteLine("The goblin struck you with his mace and left you with " + playerHp + "HP left!");
} while (playerHp > 0 || enemyHp > 0);
You need to store the result of Console.ReadLine before testing its value:
string line = Console.ReadLine();
if (line == "1")
{
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
}
else if (line == "2")
{
Console.WriteLine("You prepaired your sheild for the incoming attack");
}
else if (line == "3")
{
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!" );
}
Otherwise your program will call Console.ReadLine 3 times and prompt the user 3 times in the worst case.
Console.ReadLine() will prompt for input every time you call it.
You can use a switch statement instead to ask for input once and compare it against every value you want to handle:
switch (Console.ReadLine())
{
case "1":
// ...
break;
case "2":
// ...
break;
// Add rest of cases here
}
Basically, you are evaluating each Console.Readline() each time the user enters a value. So, user enter 2, if (Console.ReadLine() == "1") evaluates to false. Enters 2 again, else if (Console.ReadLine() == "2") evaluates to true. As others have stated, use Console.ReadLine() once per loop, store the value, and check it in your if statements:
string userinput = Console.ReadLine();
if(userinput == "1")
// do stuff
else if(userinput == "2")
// do other stuff
//etc.
I suggest you to use a switch
The problem was the fact that you repeated 3 time Console.ReadLine() instead of storing and using its value!
Plus, I added a check of the user input, you didn't think about the possibility to have an invalid input!
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int playerHp = 100;
int enemyHp = 100;
int playerD = rnd.Next(10, 15);
int enemyD = rnd.Next(10, 15);
int potion = 25;
Console.Write("Get Ready! It's time to battle! ");
Console.WriteLine("You stare into the eyes of the ugly goblin and are ready to slay it with your sword \n");
do
{
Console.WriteLine(" what will you do now?");
Console.WriteLine("\n 1. Attack 2. Defend 3. Use potion");
bool isInputValid = false;
while (isInputValid == false)
{
isInputValid = true;
switch (Console.ReadLine())
{
case "1":
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
break;
case "2":
Console.WriteLine("You prepaired your sheild for the incoming attack");
break;
case "3":
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!");
break;
default:
Console.WriteLine("Invalid input, please choose a listed action!");
isInputValid = false;
break;
}
}
Console.WriteLine("\nEnemy Turn!");
playerHp -= enemyD;
Console.WriteLine("The goblin struck you with his mace and left you with " + playerHp + "HP left!");
} while (playerHp > 0 || enemyHp > 0);
}
}

I created a multiple choice c# console program and i placed a bonus stage but when it reaches it nothing shows up

I created a multiple choice c# console program and i placed a bonus stage which triggers if you score perfect 5 points but when it reaches it nothing shows up.
why?
all the other if's work except the bonus one can someone tell me how to resolve this?.
Sorry if my coding is very newbieish (int,string,if)
{
int score = 0;
string ansr1 = "";
string ansr2 = "";
string ansr3 = "";
string ansr4 = "";
string ansr5 = "";
string bonus1 = "";
Console.WriteLine("Welcome to my quiz user!(please type your'e answers in lower case letters)\nWhat is your'e name?\n");
string name = Console.ReadLine();
Console.Clear();
Console.WriteLine("Okay "+name+" lets start!\n");
Console.Beep(500, 500);
Console.Beep(500, 500);
Console.Beep(500, 500);
Console.Beep(660, 2500);
Console.Clear();
//no.1
Console.WriteLine("Question 1\nWhat colour is the sky "+name+"?\na.blue\nb.green\nc.red\n");
ansr1 = Console.ReadLine();
Console.Clear();
if (ansr1 == "a")
{
score = score + 1;
Console.WriteLine("Correct!\n"+name+"'s score:"+score+"\n");
}
else
{
Console.WriteLine("Wrong!\n"+name+"'s score:"+score+"\n");
}
Console.Beep(600, 1500);
Console.Clear();
//no.2
Console.WriteLine("Question 2\nHow many stars are there on the american flag "+name+"?\na.21\nb.72\nc.50\n");
ansr2 = Console.ReadLine();
Console.Clear();
if (ansr2 == "c")
{
score = score+1;
Console.WriteLine("Correct\n"+name+"'s score:"+ score+"\n");
}
else
{
Console.WriteLine("Wrong\n"+name+"'s score:"+score+"\n");
}
Console.Beep(700, 1500);
Console.Clear();
//no.3
Console.WriteLine("Question 3\n"+name+",If you were in third place and you over take someone in second place what place would you be in now?\na.first\nb.second\nc.third\n");
ansr3 = Console.ReadLine();
Console.Clear();
if (ansr3 == "b")
{
score = score+1;
Console.WriteLine("Correct\n"+name+"'s score:" + score+"\n");
}
else
{
Console.WriteLine("Wrong\n"+name+"'s score:" + score+"\n");
}
Console.Beep(800, 1500);
Console.Clear();
//no.4
Console.WriteLine("Question 4\n" + name + ",what is the tallest mountain in the world?\na.Everest\nb.Fuji\nc.Bromo\n");
ansr4 = Console.ReadLine();
Console.Clear();
if (ansr4 == "a")
{
score = score + 1;
Console.WriteLine("Correct\n" + name + "'s score:" + score + "\n");
}
else
{
Console.WriteLine("Wrong\n" + name + "'s score:" + score + "\n");
}
Console.Beep(900, 1500);
Console.Clear();
//no.5
Console.WriteLine("Question 3\n" + name + ",If you were in third place and you over take someone in second place what place would you be in now?\na.first\nb.second\nc.third\n");
ansr5 = Console.ReadLine();
Console.Clear();
if ((ansr5 == "b") && (score == 5))
{
//bonus level
Console.WriteLine("Congratulations" + name + "you have scored a perfect 5!\nWould you like to enter the bonus stage?\nIf you lose this you lose the game\nbut if you pass you will receive 5 points.\nYes, or No?");
bonus1 = Console.ReadLine();
if (bonus1 == "yes")
{
}
else
{
Console.WriteLine();
}
}
else if (ansr5 == "b")
{
score = score + 1;
Console.WriteLine("Correct\n" + name + "'s score:" + score + "\n");
}
else
{
Console.WriteLine("Wrong\n" + name + "'s score:" + score + "\n");
}
Console.Beep(1000, 1500);
Console.Clear();
Console.ReadKey();
}
}
}
Your best score can only be 4 while you are checking for score==5 for bonus. I think you forgot to increment score after fifth question. Either you have to check for score==4 or increment score after 5th question. Here is updated code.
{
int score = 0;
string ansr1 = "";
string ansr2 = "";
string ansr3 = "";
string ansr4 = "";
string ansr5 = "";
string bonus1 = "";
Console.WriteLine("Welcome to my quiz user!(please type your'e answers in lower case letters)\nWhat is your'e name?\n");
string name = Console.ReadLine();
Console.Clear();
Console.WriteLine("Okay "+name+" lets start!\n");
Console.Beep(500, 500);
Console.Beep(500, 500);
Console.Beep(500, 500);
Console.Beep(660, 2500);
Console.Clear();
//no.1
Console.WriteLine("Question 1\nWhat colour is the sky "+name+"?\na.blue\nb.green\nc.red\n");
ansr1 = Console.ReadLine();
Console.Clear();
if (ansr1 == "a")
{
score = score + 1;
Console.WriteLine("Correct!\n"+name+"'s score:"+score+"\n");
}
else
{
Console.WriteLine("Wrong!\n"+name+"'s score:"+score+"\n");
}
Console.Beep(600, 1500);
Console.Clear();
//no.2
Console.WriteLine("Question 2\nHow many stars are there on the american flag "+name+"?\na.21\nb.72\nc.50\n");
ansr2 = Console.ReadLine();
Console.Clear();
if (ansr2 == "c")
{
score = score+1;
Console.WriteLine("Correct\n"+name+"'s score:"+ score+"\n");
}
else
{
Console.WriteLine("Wrong\n"+name+"'s score:"+score+"\n");
}
Console.Beep(700, 1500);
Console.Clear();
//no.3
Console.WriteLine("Question 3\n"+name+",If you were in third place and you over take someone in second place what place would you be in now?\na.first\nb.second\nc.third\n");
ansr3 = Console.ReadLine();
Console.Clear();
if (ansr3 == "b")
{
score = score+1;
Console.WriteLine("Correct\n"+name+"'s score:" + score+"\n");
}
else
{
Console.WriteLine("Wrong\n"+name+"'s score:" + score+"\n");
}
Console.Beep(800, 1500);
Console.Clear();
//no.4
Console.WriteLine("Question 4\n" + name + ",what is the tallest mountain in the world?\na.Everest\nb.Fuji\nc.Bromo\n");
ansr4 = Console.ReadLine();
Console.Clear();
if (ansr4 == "a")
{
score = score + 1;
Console.WriteLine("Correct\n" + name + "'s score:" + score + "\n");
}
else
{
Console.WriteLine("Wrong\n" + name + "'s score:" + score + "\n");
}
Console.Beep(900, 1500);
Console.Clear();
//no.5
Console.WriteLine("Question 3\n" + name + ",If you were in third place and you over take someone in second place what place would you be in now?\na.first\nb.second\nc.third\n");
ansr5 = Console.ReadLine();
Console.Clear();
if ((ansr5 == "b") && (score == 4))
{
//bonus level
Console.WriteLine("Congratulations" + name + "you have scored a perfect 5!\nWould you like to enter the bonus stage?\nIf you lose this you lose the game\nbut if you pass you will receive 5 points.\nYes, or No?");
bonus1 = Console.ReadLine();
if (bonus1 == "yes")
{
}
else
{
Console.WriteLine();
}
}
else if (ansr5 == "b")
{
score = score + 1;
Console.WriteLine("Correct\n" + name + "'s score:" + score + "\n");
}
else
{
Console.WriteLine("Wrong\n" + name + "'s score:" + score + "\n");
}
Console.Beep(1000, 1500);
Console.Clear();
Console.ReadKey();
}
}

Bug when reading password with confirmation and retries in a loop

EDIT: The problem I am facing is that I enter an incorrect password to confirm previous password and it works since it is the first try. The max is 3 tries. During 2nd and 3rd try even if password is correct it will say invalid password.
I do not want that
I know I am missing something very trivial but I cannot manage to find it. This is the code:
class Program
{
static void Main(string[] args)
{
string username = "";
string pass = "";
string confirmPass = "";
Console.Write("Enter username: ");
username = Console.ReadLine();
Console.WriteLine();
Console.Write("Enter your password: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pass += key.KeyChar;
Console.Write("*");
}
else if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
pass = pass.Substring(0, (pass.Length - 1));
Console.Write("\b \b");
}
// Stops Receving Keys Once Enter is Pressed
} while (key.Key != ConsoleKey.Enter);
Console.WriteLine("");
Console.WriteLine("Confirm your password: ");
ConsoleKeyInfo confirmKey;
int retryCount = 3;
string finalPass = "";
do{
confirmKey = Console.ReadKey(true);
// Backspace Should Not Work
if (confirmKey.Key != ConsoleKey.Backspace && confirmKey.Key != ConsoleKey.Enter)
{
confirmPass += confirmKey.KeyChar;
Console.Write("*");
}
else if (confirmKey.Key == ConsoleKey.Backspace && pass.Length > 0)
{
confirmPass = confirmPass.Substring(0, (confirmPass.Length - 1));
Console.Write("\b \b");
}
//
// Stops Receving Keys Once Enter is Pressed
} while ((confirmKey.Key != ConsoleKey.Enter));
//Console.WriteLine("");
//string confirmPass = "";
do
{
if (confirmPass != pass)
{
Console.WriteLine("Re-enter Password: (" + retryCount + " tries remaining)");
do
{
confirmKey = Console.ReadKey(true);
// Backspace Should Not Work
if (confirmKey.Key != ConsoleKey.Backspace && confirmKey.Key != ConsoleKey.Enter)
{
confirmPass += confirmKey.KeyChar;
Console.Write("*");
}
else if (confirmKey.Key == ConsoleKey.Backspace && pass.Length > 0)
{
confirmPass = confirmPass.Substring(0, (confirmPass.Length - 1));
Console.Write("\b \b");
}
//
// Stops Receving Keys Once Enter is Pressed
} while ((confirmKey.Key != ConsoleKey.Enter));
retryCount--;
}
else if (confirmPass == pass)
{
Console.WriteLine("Enter password to log in :");
finalPass = Console.ReadLine();
if (finalPass == pass)
{
Console.WriteLine("Login Successful. Welcome " + username + "!");
Console.WriteLine();
Console.WriteLine("Test Successful. Press Enter to quit.");
}
}
if (retryCount == 0)
{
Console.WriteLine("Exceeded number of tries!!");
Console.ReadLine();
}
} while (confirmPass != pass && retryCount != 0);
}
}
Based on your code, this is what I came up with:
public static void Main(string[] args)
{
string username = "";
string pass = "";
string confirmPass = "";
Console.Write("Enter username: ");
username = Console.ReadLine();
Console.WriteLine();
Console.Write("Enter your password: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pass += key.KeyChar;
Console.Write("*");
}
else if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
pass = pass.Substring(0, (pass.Length - 1));
Console.Write("\b \b");
}
// Stops Receving Keys Once Enter is Pressed
} while (key.Key != ConsoleKey.Enter);
Console.WriteLine("");
Console.WriteLine("Confirm your password: ");
ConsoleKeyInfo confirmKey;
int retryCount = 3;
string finalPass = "";
do
{
confirmKey = Console.ReadKey(true);
// Backspace Should Not Work
if (confirmKey.Key != ConsoleKey.Backspace && confirmKey.Key != ConsoleKey.Enter)
{
confirmPass += confirmKey.KeyChar;
Console.Write("*");
}
else if (confirmKey.Key == ConsoleKey.Backspace && pass.Length > 0)
{
confirmPass = confirmPass.Substring(0, (confirmPass.Length - 1));
Console.Write("\b \b");
}
// Stops Receving Keys Once Enter is Pressed
} while ((confirmKey.Key != ConsoleKey.Enter));
do
{
if (confirmPass != pass)
{
confirmPass = "";
Console.WriteLine("Re-enter Password: (" + retryCount + " tries remaining)");
do
{
confirmKey = Console.ReadKey(true);
// Backspace Should Not Work
if (confirmKey.Key != ConsoleKey.Backspace && confirmKey.Key != ConsoleKey.Enter)
{
confirmPass += confirmKey.KeyChar;
Console.Write("*");
}
else if (confirmKey.Key == ConsoleKey.Backspace && pass.Length > 0)
{
confirmPass = confirmPass.Substring(0, (confirmPass.Length - 1));
Console.Write("\b \b");
}
// Stops Receving Keys Once Enter is Pressed
} while ((confirmKey.Key != ConsoleKey.Enter));
retryCount--;
}
else if (confirmPass == pass)
{
Console.WriteLine("Enter password to log in :");
finalPass = Console.ReadLine();
if (finalPass == pass)
{
Console.WriteLine("Login Successful. Welcome " + username + "!");
Console.WriteLine();
Console.WriteLine("Test Successful. Press Enter to quit.");
Console.ReadLine();
break;
}
}
if (retryCount == 0)
{
Console.WriteLine("Exceeded number of tries!!");
Console.ReadLine();
}
} while (retryCount != 0);
}
Basically I made the following changes:
When you enter that last do loop, and enter the first if statement, I set confirmPass = "";. This is the reason your code did not do that part initially, because you were appending their new confirmPass to the original. Thus, if they typed password, then password2, then to retry they typed password, confirmPass was password2password.
After changing this, the flow did not work correctly, so I removed the confirmPass != pass && bit from that while. This allowed you to get to the elseif portion in that loop.
Still, I assume this was a bit wrong as once you hit that elseif it would infinite loop. So I told it to break inside that elseif which kills that do/while loop.
If this solution is not correct, please clarify your requirements so that we may better assist you.
Your program is rather convoluted, which is why it will be much harder to spot any errors. You should really learn how to use sub routines (i.e. functions), so that you don't have to repeat blocks of code that do the same thing over and over again (like reading a password).
If we were to refactor your code a little bit, by moving those repeated parts out into a method named ReadPassword, like this:
public static string ReadPassword()
{
var pass = "";
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
// Stop Receving Keys Once Enter is Pressed
break;
// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace)
{
pass += key.KeyChar;
Console.Write("*");
}
else if (pass.Length > 0)
{
pass = pass.Substring(0, (pass.Length - 1));
Console.Write("\b \b");
}
}
return pass;
}
And used it to replace all those do ... while loops used for reading a password, without changing anything else in your code (so the bugs are still there):
public static void Main(params string[] args)
{
string username = "";
string pass = "";
string confirmPass = "";
Console.Write("Enter username: ");
username = Console.ReadLine();
Console.WriteLine();
Console.Write("Enter your password: ");
pass = ReadPassword(); // changed to function call
Console.WriteLine("");
Console.WriteLine("Confirm your password: ");
int retryCount = 3;
string finalPass = "";
confirmPass = ReadPassword(); // changed to function call
do
{
if (confirmPass != pass) // <==== this is performed before the "else"
{
Console.WriteLine("Re-enter Password: (" + retryCount + " tries remaining)");
confirmPass = ReadPassword(); // changed to function call
retryCount--;
}
else if (confirmPass == pass) // <==== "else": bug
{
// Bug: it will only get here, if the confirmed password
// was entered correctly the first time
Console.WriteLine("Enter password to log in :");
finalPass = Console.ReadLine();
if (finalPass == pass)
{
Console.WriteLine("Login Successful. Welcome " + username + "!");
Console.WriteLine();
Console.WriteLine("Test Successful. Press Enter to quit.");
}
// else <==== now what?
}
if (retryCount == 0)
{
Console.WriteLine("Exceeded number of tries!!");
Console.ReadLine();
}
} while (confirmPass != pass && retryCount != 0);
}
Now the bugs become much easier to spot. I highlighted them using <=== in the comments. I will leave it to you to figure out what is wrong, and how you can fix it.

C# program for guessing coin toss

I'm a beginner with programming so any hints would be greatly appreciated!
I'm trying to create a program where the user guesses whether a 'coin toss' will produce heads (0) or tails (1) using a random number generator and a loop as the 'coin'. The program must output the percent of correct guesses out of the total games played.
I've tried many different ways and it's far from right! It's v discouraging.
Thanks in advance for any tips!!
-C
This is basically the closest I've come:
for (numPlays = 0; ; numPlays++)
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
userChoice = Convert.ToChar(Console.ReadLine());
if (userChoice == 'H' || userChoice == 'h')
{
if (compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
Console.WriteLine("\nYOU LOSE");
if (userChoice == 'Q' || userChoice == 'q')
if (compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
Console.WriteLine("\nYOU LOSE");
if (userChoice == 'q' || userChoice == 'Q')
{
percentWin = (double)(numWins / numPlays);
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
}
}
}
Console.ReadKey();
}
}
I optimized your code a little bit,I hope this helps:
int numPlays = 0, numWins = 0;
int compChoice = 0;
char userChoice;
double percentWin;
Random rnd = new Random();
while (true)
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
userChoice = Console.ReadKey().KeyChar;
compChoice = rnd.Next(0, 2);
if (char.ToLowerInvariant(userChoice) != 'q')
{
if (char.ToLowerInvariant(userChoice) == 'h' && compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else if (char.ToLowerInvariant(userChoice) == 't' && compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
numPlays++;
}
else
{
percentWin = (double) numWins/numPlays;
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
break;
}
}
I think you don't need an explanation, all of the code is self-explanatory.But you have an obvious mistake when you calculating the percentage:
percentWin = (double)(numWins / numPlays);
Here you are performing an integer division,then casting that result to double,it's pointless because you already lose your decimal points.Instead you should cast one of the operands to double so it will perform a double division and you will get the correct result.
Just invoke this method and play your game!
public static void SomeMethod()
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
char userChoice;
int numWins = 0;
int numPlays = 0;
double percentWin = 0d;
while ((userChoice = Convert.ToChar(Console.ReadLine())).ToString().ToLower() != "q")
{
numPlays++;
int compChoice = new Random().Next(2);
if (userChoice == 'H' || userChoice == 'h')
{
if (compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
continue;
}
if (userChoice == 'T' || userChoice == 't')
{
if (compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
continue;
}
}
if (numPlays != 0)
{
percentWin = (double)numWins / numPlays;
}
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
Console.ReadKey();
}
This should not be any difficult, you just need to make a clear algorithm
Let me suggest one
Char playOrExit= 'y'
Int32 gameCount = 0;
Int32 Wins = 0;
While (playOrExit.ToUpper.Equals('Y'))
{
Console.Write("Press Y to continue playing and N to exit");
playOrExit = Convert.ToChar(Console.ReadLine());
//Computer choice will be math.random from 0 and 1
//now take user choice
//compare and show if he won or lost
}
if(gameCount >0)
{
Console.WriteLine("\nYou played {0} times, out of which {1} game(s) were won.", gameCount,Wins);
}

Categories

Resources