am trying to make a hangman game where it picks a random word from a text file of words. It then displays the word in asterisks and asks the user to guess each letter of the word if they guess right it uncovers that letter.They keep playing until they guess all the letters in the word.After the word is guessed it will display the number of misses and ask if they want to play again.
The Problem I am having is when the word is guessed correctly it just keeps asking for a letter even if the word is uncovered. I am not sure how to fix this. I would like to do this without using linq if possible.
any help would be appericated
static void Main(string[] args)
{
char[] guessed = new char[26];
char guess = ' ';
char playAgain= ' ';
bool validLetterInput = false;
bool validAnswer = false;
int amountMissed = 0, index = 0;
do
{
// initilization of word and testword so that we could generate a testword with the same length as original
char[] word = RandomLine().Trim().ToCharArray();
char[] testword = new string('*', word.Length).ToCharArray();
char[] copy = word;
Console.WriteLine(testword);
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
//Check if the 2 arrays are equal
while (testword != word)
{
while (!validLetterInput)
{
try
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine().ToLower());
//Checks if guess is letter or not
if (((guess >= 'A' && guess <= 'Z') || (guess >= 'a' && guess <= 'z')))
{
validLetterInput = true;
}
else
{
Console.WriteLine("Invalid Input");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
validLetterInput = false;
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {string.Join("",testword)}. You missed {amountMissed} times.");
while (!validAnswer)
{
try
{
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
if(playAgain == 'y' || playAgain == 'Y' || playAgain == 'n' || playAgain == 'N')
{
validAnswer = true;
}
else
{
Console.WriteLine("Invalid input try again");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
validAnswer = false;
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
}
public static string RandomLine()
{
// store text file in an array and return a random value
string[] lines = File.ReadAllLines("E:\\Amimals1.csv");
Random rand = new Random();
return lines[rand.Next(lines.Length)].ToLower();
}
}
There are various ways to compare two arrays / lists. Simple method i see for character arrays / lists is to convert them to strings and then compare.
Array Comparison thread on stackoverflow
testword.ToString() != word.ToString()
In regards to what Flydog57, use this link to learn how to debug code:
Compare the arrays with "SequenceEqual" instead of !=. This way you will need to change your while statement to:
while (!testword.SequenceEqual(word))
This is noted by Quartermeister and further explained by ohn Buchanan in the question "Easiest way to compare arrays in C#". link is here:
Easiest way to compare arrays in C#
Otherwise great program!
Note when you are trying debugging, a simple thing I like to put in there is a write of what response I want to see initially if I cannot figure out through debug. you can always remove the line later. I put this at the end of the while statement.
Console.WriteLine(testword.SequenceEqual(word));
Related
This program randomly creates a number between 1 and 50 that the user needs to guess. I want to restart the while loop when the user's guess is incorrect. I have tried using break and continue to do this, but either I am doing it wrong or it is not the best solution. Also, when the user input is incorrect they are asked if they want to guess again. I also tried exiting that loop with break or continue with similar results. Any suggestions?
Console.WriteLine("I am thinking of a whole number between 1 and 50. Enter your guess.");
string userGuess;
Random rnd = new Random();
int compNum = rnd.Next(1, 50);
int guessToInt;
int numOfTries = 0;
string cont;
bool correct = false;
//TODO Delete this line when finished
Console.WriteLine($"Answer " + compNum);
//Trying to get new user input if guess is wrong
while (correct == false)
{
//correct = false;
numOfTries++;
userGuess = Console.ReadLine();
guessToInt = Int32.Parse(userGuess);
if (guessToInt == compNum)
{
numOfTries++;
correct = true;
Console.WriteLine($"Your guess is correct! The number was " + compNum + ". Congratulations. It only took you " + numOfTries + " guess(es).");
}
else if (guessToInt < 1 || guessToInt > 50)
{
Console.WriteLine("Incorrect input. Enter a whole number between 1 and 50. Try again.");
//numOfTries++;
correct = false;
continue;
}
else if (guessToInt != compNum)
{
//How do I get new user input?
Console.WriteLine("Your guess is incorrect. Would you like to try again? Y or N?");
//numOfTries++;
correct = false;
cont = Console.ReadLine();
if (cont == "Y")
{
continue;
}
else Console.WriteLine("Bye."); Environment.Exit(0);
}
}
Few problems:
You don't have to set the boolean to false each time. It is already set to false at start
else Console.WriteLine("Bye."); Environment.Exit(0);
Since you didn't add curly brackets (which I strongly advise you to never do),
Only the first command will operate under the statement.
The "Environment.Exit" will always occur.
For the rest, I added the fixes to your code.
Console.WriteLine("I am thinking of a whole number between 1 and 50. Enter your guess.");
string userGuess;
Random rnd = new Random();
int compNum = rnd.Next(1, 50);
int guessToInt;
int numOfTries = 0;
string cont;
bool correct = false;
//TODO Delete this line when finished
Console.WriteLine($"Answer " + compNum);
//Trying to get new user input if guess is wrong
while (correct == false)
{
//correct = false;
numOfTries++;
userGuess = Console.ReadLine();
guessToInt = Int32.Parse(userGuess);
if (guessToInt == compNum)
{
numOfTries++;
correct = true;
Console.WriteLine($"Your guess is correct! The number was " + compNum + ". Congratulations. It only took you " + numOfTries + " guess(es).");
}
else if (guessToInt < 1 || guessToInt > 50)
{
Console.WriteLine("Incorrect input. Enter a whole number between 1 and 50. Try again.");
//numOfTries++;
//**correct = false; --> No need, correct was already false
//**continue; --> No need, will continue anyway
}
else if (guessToInt != compNum)
{
//How do I get new user input?
Console.WriteLine("Your guess is incorrect. Would you like to try again? Y or N?");
cont = Console.ReadLine();
//numOfTries++;
//**correct = false; --> No need, correct was already false
//** if (cont == "Y") --> No need, will continue anyway
//** {
//** continue;
//** }
// else Console.WriteLine("Bye."); Environment.Exit(0); -->
//** "else" without brackets will
if (cont != "Y")
{
break;
}
Console.WriteLine("Enter your next guess:");
}
}
NOTE: I haven't touched the "numOfTries" feature since not mentioned in the question
Is there a way to ignore a line/block of code if the condition is met?
I'm doing a C# .NET tutorial, and the application is a number guessing game.
I added a hint option if the user enters a wrong number (else if part):
// While guess is not correct
while (guess != correctNumber)
{
//Get users input
string input = Console.ReadLine();
// Make sure it's a number
if (!int.TryParse(input, out guess))
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Please use an actual number");
// Keep going
continue;
}
// Cast to int and put in guess
guess = Int32.Parse(input);
// Check if guess is close to correct number
if(guess == correctNumber + 2 || guess == correctNumber - 2)
{
// Tell the user that he is close
PrintColorMessage(ConsoleColor.DarkCyan, "You are close!!");
}
// Match guess to correct number
else if (guess != correctNumber)
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again");
AskForAHint(correctNumber);
}
}
// Print success message
PrintColorMessage(ConsoleColor.Yellow, "You are CORRECT!");
Basically I am asking a user if he wants a hint, and if he writes Y, the hint will be displayed. However, is there an option to display this question only once since this if statement is included in a while loop?
It would be annoying if "Do you want a hint?" question keeps displaying even if the user says Y.
My AskForAHint function:
static void AskForAHint(int num)
{
// Ask user if he wants a hint
Console.WriteLine("Do you want a hint? [Y/N]");
// Take his answer
string ans = Console.ReadLine().ToUpper();
// If the user wants a hint
if (ans == "Y")
{
// First hint number
int beginning = (num - num % 10);
// Second hint number
int finish = beginning + 10;
// Give user a hint
Console.WriteLine("The correct number is somewhere betweer {0} and {1}", beginning, finish);
}
else if (ans == "N")
{
return;
}
}
Thanks
Another way to do it would be to make the number of hints configurable (allowing the caller to specify how many hints they want to let the user ask for), and then keep track of the number of hints given in the method itself.
This would require a slight change to the AskForAHint method, however, since we don't know if the user answered "Y" or "N" to the hint question. Since AskForHint has no return value, we could have it return a bool that indicates how the user responded to the question:
static bool AskForAHint(int num)
{
var answer = GetUserInput("Do you want a hint? [Y/N]: ", ConsoleColor.Yellow);
if (!answer.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
{
return false;
}
var beginning = num - num % 10;
var finish = beginning + 10;
Console.WriteLine($"The correct number is somewhere between {beginning} and {finish}");
return true;
}
Now we can keep track of how many hints the user has received by incrementing a counter in our "Game" method:
// Only ask for a hint if they have any hints (and guesses) remaining
if (hintCount < maxHints && guessCount < maxGuesses)
{
// If they asked for a hint, increase the hint count
if (AskForAHint(correctNumber)) hintCount++;
// If they didn't want a hint, max out hint count so we don't ask again
else hintCount = maxHints;
}
To test out the sample code above, I used this method below, which also allows us to configure how many total guesses the user has, what the min and max values of the range should be, and if they should be given a "directional hint", like "too high!" or "too low!":
private static readonly Random Random = new Random();
private static void PlayGuessingGame(int maxHints = 1, int maxGuesses = 10,
int rangeMin = 1, int rangeMax = 100, bool giveDirectionalHint = true)
{
if (rangeMax < rangeMin) rangeMax = rangeMin;
var correctNumber = Random.Next(rangeMin, rangeMax + 1);
var guessCount = 0;
var hintCount = 0;
WriteMessage("Welcome to the guessing game!", ConsoleColor.White);
WriteMessage("-----------------------------\n", ConsoleColor.White);
WriteMessage($"I'm thinking of a number from {rangeMin} to {rangeMax}. ", ConsoleColor.Green);
WriteMessage("Let's see how many guesses it takes you to guess it!\n", ConsoleColor.Green);
do
{
WriteMessage($"(You have {maxGuesses - guessCount} guesses left)");
var input = GetUserInput("Enter the number I'm thinking of: ", ConsoleColor.White);
int guess;
if (!int.TryParse(input, out guess))
{
WriteMessage("Please enter a whole number", ConsoleColor.Red);
continue;
}
// Only increment guesses if they entered an actual number
guessCount++;
if (guess == correctNumber) break;
if (Math.Abs(guess - correctNumber) == 2)
{
WriteMessage("You are close!!", ConsoleColor.DarkCyan);
}
if (giveDirectionalHint)
{
WriteMessage("Wrong number - too " + (guess < correctNumber ? "low!" : "high!"),
ConsoleColor.Red);
}
else
{
WriteMessage("Wrong number, please try again", ConsoleColor.Red);
}
// Only ask for a hint if they have any hints (and guesses) remaining
if (hintCount < maxHints && guessCount < maxGuesses)
{
// If they asked for a hint, increase the hint count
if (AskForAHint(correctNumber)) hintCount++;
// If they didn't want a hint, max out hint count so we don't ask again
else hintCount = maxHints;
}
} while (guessCount < maxGuesses);
WriteMessage("You are CORRECT!", ConsoleColor.Yellow);
GetKeyFromUser("\nDone! Press any key to exit...");
}
This uses the helper functions:
public static void WriteMessage(string message, ConsoleColor color = ConsoleColor.Gray)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ResetColor();
}
private static string GetUserInput(string prompt, ConsoleColor color = ConsoleColor.Gray)
{
Console.ForegroundColor = color;
Console.Write(prompt);
Console.ResetColor();
return Console.ReadLine();
}
Output
You can see in the output below, I was only given a single hint. However that, combined with the directional hints, made the game easy to win:
I think you can do an "if" with a counter.
Try It
Int cont = 0; //global
// While guess is not correct
while (guess != correctNumber)
{
//Get users input
string input = Console.ReadLine();
// Make sure it's a number
if (!int.TryParse(input, out guess))
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Please use an actual number");
// Keep going
continue;
}
// Cast to int and put in guess
guess = Int32.Parse(input);
// Check if guess is close to correct number
if(guess == correctNumber + 2 || guess == correctNumber - 2)
{
// Tell the user that he is close
PrintColorMessage(ConsoleColor.DarkCyan, "You are close!!");
}
// Match guess to correct number
else if (guess != correctNumber)
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again");
if(cont == 0){
AskForAHint(correctNumber);
}
}
}
// Print success message
PrintColorMessage(ConsoleColor.Yellow, "You are CORRECT!");
And in the function add
static void AskForAHint(int num)
{
// Ask user if he wants a hint
Console.WriteLine("Do you want a hint? [Y/N]");
// Take his answer
string ans = Console.ReadLine().ToUpper();
// If the user wants a hint
if (ans == "Y")
{
cont = 1;
// First hint number
int beginning = (num - num % 10);
// Second hint number
int finish = beginning + 10;
// Give user a hint
Console.WriteLine("The correct number is somewhere betweer {0} and {1}", beginning, finish);
}
else if (ans == "N")
{
return;
}
}
Use a Member Variable Boolean, its similar to how you can avoid recursive calls.
private bool alreadyHinted = false;
static void AskForAHint(int num)
{
if (alreadyHinted) return;
alreadyHinted = true;
At some point you will need to set alreadyHinted back to false;
I am making a program for a hangman game that picks a random word from a text file of words and then asks the user to guess each letter of the word. Each letter in the word is displayed with an asterisk and when the user makes a correct guess the actual letter is then displayed. After the word is guessed it will then display the number of times missed and ask the user if they want to guess another word.
I have the asterisks hard coded but I would like the asterisks to be the same length of the random word chosen from the text file. I am not sure how I would do this
Any help would be appreciated.
static void Main(string[] args)
{
char[] guessed = new char[26];
char[] testword = "******".ToCharArray();
char[] word = RandomLine().ToCharArray();
char[] copy = word;
char guess;
char playAgain;
int amountMissed = 0, index = 0;
Console.WriteLine(testword);
do
{
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
while (testword != word)
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {copy}. You missed {amountMissed} times.");
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
}
public static string RandomLine()
{
try
{
// store text file in an array and return a random value
string[] lines = File.ReadAllLines("C:\\Intel\\Advanced1.csv");
Random rand = new Random();
return lines[rand.Next(lines.Length)];
}
catch (Exception e)
{
Console.WriteLine("The file could not be read");
Console.WriteLine(e.Message);
}
}
To display the coded word (with asterisks) with same length as word, you could use
char[] testword = new string('*',word.Length).ToCharArray();
Making few other corrections in your code
char[] guessed = new char[26];
char guess;
char playAgain;
int amountMissed = 0, index = 0;
do
{
char[] word = RandomLine().ToCharArray(); // Change :This needs to be inside the loop so that new random word could be selected user selects to continue the game
char[] testword = new string('*',word.Length).ToCharArray(); // Change : Reordered initilization of word and testword so that we could generate testword with same length as original
char[] copy = word;
Console.WriteLine(testword);
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
while (!testword.SequenceEqual(word)) // Change : Comparison of arrays
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {copy}. You missed {amountMissed} times.");
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
This way:
class Program
{
static void Main(string[] args)
{
bool found = false;
string originalWord = "test";
char[] word = originalWord.ToCharArray();
char[] asteriskedWord = new string('*', word.Length).ToCharArray();
while (found == false)
{
Console.WriteLine(asteriskedWord);
string input = Console.ReadLine();
if (input.Length != 1)
{
Console.WriteLine("Your input can be only one char.");
}
else
{
char c = char.Parse(input);
for (int i = 0; i < word.Length; i++)
{
if (word[i] == c)
{
asteriskedWord[i] = c;
word[i] = '*';
int missingCharsAmount = asteriskedWord.Count(x => x == '*');
Console.WriteLine("Correct, missing " + missingCharsAmount + " chars.");
if (missingCharsAmount == 0)
{
found = true;
}
break;
}
}
}
}
}
}
The policies im trying to apply are that it has to be 3 characters long, that it must include a lower case letter, an upper case letter and a number in any order. Im trying to use it as a method to read in a password set by the user for an assignment.I have written as much as i can to emiminate errors but i cant figure out a way to apply said policies. this is what i have so far... Any help would be greatly appreciated
private static string readPass() { //readpass method to read in password of 1 lower case, 1 upper case & 1 number
bool validInput = true;
char letterUserInput; //letter from string
int asciiCodeLetter; //number code for letter
string userInput;
do {
validInput = true;
userInput = Console.ReadLine();
try {
if (userInput.Length < 1) {
validInput = false;
Console.WriteLine("You have just pressed Enter Please Enter a valid Password");
} //if check length
else if (userInput.Length > 1 && userInput.Length < 3) {
validInput = false;
Console.WriteLine("Password Is Too Short. Please Enter Valid Password");
} //if check length too short
else if (userInput.Length > 3)
{
validInput = false;
Console.WriteLine("Password Is Too Long. Please Enter A Valid Password");
} //if check length too short
for (int i = 0; i < userInput.Length; i++) //take each letter in turn from string
{
letterUserInput = userInput[i];
asciiCodeLetter = Convert.ToInt16(letterUserInput);
if (asciiCodeLetter < 48 || asciiCodeLetter > 57)
{
validInput = false;
Console.WriteLine("You have used an invalid character.\n Password Must Contain 1 Upper Case, 1 Lower Case letter and 1 Number)");
} //character check with ASCII
}
}
catch
{
validInput = false;
Console.WriteLine("An unspecified error has occured");
} //catch
if (validInput == false) Console.Write("Invalid Password. Please Enter Again = ");
} while (validInput == false); // do. repeat entry if invalid
return userInput;
}
You can use regular expressions for this:
var input = Console.ReadLine();
var regex = new System.Text.RegularExpressions.Regex("^([0-9][a-z][A-Z]|[0-9][A-Z][a-z]|[a-z][0-9][A-Z]|[a-z][A-Z][0-9]|[A-Z][a-z][0-9]|[A-Z][0-9][a-z])$");
validInput = input != null && regex.IsMatch(input);
I'm sure there are more fancy Regex for this. But this is simply enough to understand it if you are not familiar with Regex expressions.
Edit
You can use the following Regex if you want something more fancy:
var input = Console.ReadLine();
var regex = new System.Text.RegularExpressions.Regex(#"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{3}$");
validInput = input != null && regex.IsMatch(input);
Some pseudocode for this might be:
String candidatePwd = textboxPwd.Text.Trim();
Boolean validPwd = IsValidPassword(candidatePwd);
private bool IsValidPassword(String candidate)
{
return ((candidate.Length == 3) &&
(ContainsOneUppercaseLetter(candidate)) &&
(ContainsOneLowerCaseLetter(candidate)) &&
(ContainsOneNumber(candidate)));
}
private bool ContainsOneUppercaseLetter(String candidate)
{
// search for an uppercase letter; if one found, return true
}
private bool ContainsOneLowercaseLetter(String candidate)
{
// search for a lowercase letter; if one found, return true
}
private bool ContainsOneUppercaseLetter(String candidate)
{
// search for a number; if one found, return true
}
The actual implementation is left to you.
For 3 chars - simply save the password written by user as a string, then check it length. If it comes to upper case, I would convert every char on ASCII code, then check if any code is equal to the code of all upper case letters. For checking if there is a number, check every char of your password using something like this
int n; bool isNumeric = int.TryParse("123", out n);
Hope that will help.
You can use the regular expression:
^.(?=.{3,})(?=.\d)(?=.[a-z])(?=.[A-Z]).*$
and simplify your code:
if(!Regex.IsMatch(userInput, "^.*(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$")
Console.WriteLine("The password has to be 3 characters long, and must include a lower case letter, an upper case letter, and a number");
class Program
{
static void Main(string[] args)
{
string choice = string.Empty;
do
{
start:
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (number < 1000)
{
switch (conversion)
{
case true:
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
break;
case false:
Console.WriteLine("ERROR: INVALID INPUT!");
goto start;
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
return;
}
do // Here is the beginning of the do code
{
Console.WriteLine("\n Do you want to continue - Yes or No");
choice = Console.ReadLine();
if (choice.ToUpper() != "YES" && choice.ToUpper() != "NO")
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
} while (choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
} while (choice.ToUpper() == "YES");
}
}
I'm using several do while loops in this statement however I'm trumped on how I would put in a loop "ERROR INVALID INPUT:" result when a user puts in anything other than the limits of the assigned integers (i.e. putting decimals or fractions) or if they put a string. I simply used goto because I'm having trouble finding out where to put the do while loop statement. If someone could simply show me how I might replace that one goto with a do while loop then I would be very greatful. (Note if you show me ways I could optimize my code better since I'm still new I probably won't understand it but your welcome to give it your best shot!)
Short answer:
The keyword continue means to go back to the beginning of the loop. Note that this will recheck the loop condition and break if it is false. Also, most people find do-while loops less readable (and they are really rarely necessary), so try using while loops instead.
There is also the keyword break which will simply exit the loop. (not just for switch-case!)
A more readable version would look something like this:
string userAnswer = "yes";
// while is usually more readable than do-while
while (userAnswer == "yes")
{
Console.WriteLine("Please input a number for it to be counted!");
int number;
// Ask for new input until the user inputs a valid number
while (!int.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("Invalid number, try again");
}
if (number < 1000)
{
// Print from 0 to number, jumping in 2's
for (int i = 0; i <= number; i += 2)
Console.WriteLine(i + " ");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
continue; // Jump back to the start of this loop
}
Console.WriteLine("Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
// Ask for new input until the user inputs "Yes" or "No"
while (userAnswer != "yes" && userAnswer != "no")
{
Console.WriteLine("Invalid input. Continue? (Yes / No)");
userAnswer = Console.ReadLine().ToLower();
}
}
Hey I'll post some code that may help and offer some advice. Basically declare a bool named 'loopCompleted' which will continue the do while loop until you set it to true. The downside is that it will not instantly exit the loop like return/goto/etc but this is not a problem in most cases.
You may want to use if/else instead of switch(conversion), its sort of interesting to see it done that way but its a bit over the top :)
If Int.TryParse() doesnt already return false for fractional values (e.g. [15.08] returns [true] with [15] ). Then you can store Console.ReadLine() before using TryParse, then use stringName.Contains() to check for the '.' Basically, if the conversion succeeds you also check if it contained the decimal point.
Another way to check is to do float.TryParse() then check if it is a fractional value.
bool fraction = false;
if( number % 1.0f > 0)
fraction == true;
% is called modulus, it returns the remainder of A / B
If a number has a remainder when divided by 1 it must be a fractional value.
//start:
bool loopCompleted = false;
do
{
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if (conversion && number < 1000)
{
while (number <= output)
{
Console.Write(number + " ");
number += 2;
}
loopCompleted = true;
}
else
{
if(conversion == false)
{
Console.WriteLine("ERROR: INVALID INPUT!");
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
}
}
} while(!loopCompleted)