TryParse in C# and using the while loop - c#

The user Input should be within 0 to 10 and I want to use tryparse and check if the input is correct, if not then it should prompt the user again. my code is like below it only works once but if the user enters the wrong number it again executes. In this case, where should I put the loop?
int number;
bool True;
Console.Write("Enter number between 0 t0 10: ");
True = int.TryParse(Console.ReadLine(), out number);
while (number < 0 || number > 10)
{
while (True)
Console.Write("Enter number between 0 t0 10: ");
int.TryParse(Console.ReadLine(), out number);
}
{
Console.WriteLine("Please enter the correct number");
}
return number;

use do while .
int i = 0;
do
{
Console.Write("Enter number between 0 t0 10: ");
True = int.TryParse(Console.ReadLine(), out number);
} while (!True);

I'd write similar code to what you already have, but I'd rename True to isValid and use a do/while loop:
int number;
bool isValid = false;
do
{
Console.Write("Enter number between 0 and 10: ");
isValid = int.TryParse(Console.ReadLine(), out number)
&& number >= 0
&& number <= 10;
if (isValid)
{
Console.WriteLine("Please enter the correct number");
}
}
while (!isValid);
Better yet, do away with isValid altogether:
int number;
do
{
Console.Write("Enter number between 0 and 10: ");
if (int.TryParse(Console.ReadLine(), out number) && number >= 0 && number <= 10)
{
break;
}
Console.WriteLine("Please enter the correct number");
}
while (true);
Now, if the number is valid, we simply break out of the loop.
P.S. You'll see that I swaped the number conditions around to make them validity checks instead, so < became >= and > became <=.
Also, don't call a variable something like True. Imagine you're reading through a longer method and you come across this line (months after you've written it):
while (True)
That's an endless loop right? Oh no! It's the variable True, not the constant true. Now imagine further up you havebool True = false;. If you're reading quickly, you might misunderstand what the code does. Even if you're not, you have to put more mental effort into understanding what's happening.

Related

Number guessing game using TryParse

I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}

Test to ensure the user input is a double and is greater than zero?

In C# I am trying to have the user input a number. I then want to check that
They have entered a string that can be converted to a double and
They have entered a value greater than zero
The method I have initially created was
string inValue;
double outcome;
Console.WriteLine("Enter amount: ");
inValue = Console.ReadLine();
while (double.TryParse(inValue, out outcome) == false)
{
Console.WriteLine("Initial value must be of the type double");
Console.WriteLine("\nPlease enter the number again: ");
inValue = Console.ReadLine();
}
outcome = double.Parse(inValue);
while (outcome < 0)
{
Console.WriteLine("Initial value must be of at least a value of zero");
Console.WriteLine("\nPlease enter the number again: ");
inValue = Console.ReadLine();
outcome = double.Parse(inValue);
}
return outcome;
The problem was this was that if the user entered say "-10" and then "f" an exception would occur. This is because the program would move past the first check (that checks for the double) for the value of -10 but then when the "f" is entered it throws an exception when only given the second test.
I believe the solution is to create a while statement that writes the error statement when either the value cannot be converted to a double or the value is converted to a double and is below zero. What I don't know how to do is to have the value be converted to a double and then evaluated as being greater than zero all in the while statement.
You're on the right track - you need to have a single while loop that gets the input and then tries both validations. One way to do this is to create a boolean value that tracks whether or not the value is valid, and then use that as the condition for the loop:
double outcome = 0;
bool valid = false;
while (!valid)
{
Console.WriteLine("Enter amount: ");
string inValue = Console.ReadLine();
if (double.TryParse(inValue, out outcome) == false)
{
Console.WriteLine("Initial value must be of the type double");
Console.WriteLine("\nPlease enter the number again: ");
}
else if (outcome < 0)
{
Console.WriteLine("Initial value must be of at least a value of zero");
Console.WriteLine("\nPlease enter the number again: ");
}
else
{
valid = true;
}
}
return outcome;
It's also possible to put both conditions in the while statement, but this approach lets you provide a different message depending on which conditions failed.
you can or those two conditions in your first while loop
something like
while (!double.TryParse(inValue, out outcome) || outcome < 0)
{
...
}
some explanation: double.TryParse will modify the value of outcome if it is successful, so if it was able to parse then the ! TryParse will be evaluated to false, thus we get to the second part and evaluate outcome < 0.
I would go with a solution like this. Just noting that you don't have to double.Parse(Value) after you have done a double.TryParse(value, out outcome) the out parameter will populate that variable upon the TryParse being true.
You can copy and paste the below code into LinqPad and play with it. But this does what you need.
void Main()
{
var result = DoWork();
Console.WriteLine(result);
}
public double DoWork()
{
string inValue;
double outcome;
Console.WriteLine("Enter amount: ");
inValue = Console.ReadLine();
while (!double.TryParse(inValue, out outcome) || outcome <= 0)
{
Console.WriteLine("Initial value must be of the type double and greater than 0");
Console.WriteLine("\nPlease enter the number again: ");
inValue = Console.ReadLine();
}
return outcome;
}
after a little regrouping it is working code!
but i think you sometimes need to use if instead of while
string inValue = "";
double outcome = -1;
Console.WriteLine("Enter amount: ");
while (outcome < 0){
inValue = Console.ReadLine();
if (double.TryParse(inValue, out outcome) == false)
{
Console.WriteLine("Initial value must be of the type double");
Console.WriteLine("\nPlease enter the number again: ");
continue;
}
if (outcome>=0) {continue;}
Console.WriteLine("Initial value must be of at least a value of zero");
Console.WriteLine("\nPlease enter the number again: ");
}
return outcome;

Breaking out of a for loop upon invalid user entry

edit: for those who have answered, I apologize, I should have been more clear, the assignment REQUIRES use of the for loop per my professor.
I'm doing a small assignment for class and am having trouble breaking out of a for loop and prompting the user to enter a valid value. My code is set up thus far as:
const int MINRANGE = 1;
const int MAXRANGE = 20;
int input = 0;
Console.Write("Enter the desired maximum: ");
string strInput = Console.ReadLine();
Console.WriteLine("\n\n\n");
for (int.TryParse(strInput, out input); input >= MINRANGE && input <= MAXRANGE; input--)
{
Console.WriteLine("{0,2} {1,5}", input, Math.Pow(input, 3));
}
The program displays everything I need it to correctly. When the user enters a value out of the range I have specified, I need to give them a short message and then break out of the loop and return to the beginning prompt. I think I need to use something like the following if statement:
if (input >= MAXRANGE || input <= MINRANGE)
{
Console.WriteLine("That is not a valid value, please try again.");
}
Perhaps with a break; following it? But I'm not sure how to use it inside of the for loop. I've tried placing it outside, but that doesn't get me back to the user prompt, but neither does placing it inside the loop, so I'm obviously doing something wrong.
You can use a while loop
int input;
while(!int.TryParse(Console.ReadLine(), out input) || input >= MAXRANGE)
{
Console.WriteLine("Not valid!");
}
Note that this may get the user "stuck" and a helpful message as to why it isn't valid would be nice
If for some bizarre reason you must use a for loop you can use the following but it is horrible code that I would never condone
int input;
for(;;)
{
if(int.TryParse(Console.ReadLine(), out input) && input < MAXRANGE)
break;
}
Its better to do the validation before entering the loop. Try this out.....
const int MINRANGE = 1;
const int MAXRANGE = 20;
int input = 0;
Console.Write("Enter the desired maximum: ");
string strInput = Console.ReadLine();
Console.WriteLine("\n\n\n");
if (input > MAXRANGE || input < MINRANGE)
{
Console.WriteLine("That is not a valid value, please try again.");
}
else
{
for (int.TryParse(strInput, out input); input >= MINRANGE && input <=
MAXRANGE; input--)
{
Console.WriteLine("{0,2} {1,3}", input, Math.Pow(input, 3));
}
}
I would rewrite your code as follows. Creating a method for asking the input:
const int MINRANGE = 1;
const int MAXRANGE = 20;
int input = 0;
string strInput = AskInput();
while (!int.TryParse(strInput, out input)) /*while the number is invalid*/
{
Console.WriteLine("Your input is invalid. Try again.");
strInput = AskInput();
}
while (input >= MINRANGE && input <= MAXRANGE)
{
Console.WriteLine("{0,2} {1,3}", input, Math.Pow(input, 3));
input--;
}
Where AskInput is:
private static string AskInput()
{
Console.Write("Enter the desired maximum: ");
string strInput = Console.ReadLine();
Console.WriteLine("\n\n\n");
return strInput;
}
for ([(fist) Initialization];
[(second)Condition];
[(third or exit the loop) Progression])
{
[(fourth) Loop's body -if we reached third than we got here ]
}
The for loop is constructed of three parts:
The initialization part which happens only once when the loop starts.
The condition evaluation part which happens for every iteration.
The indexer progression part which also happens for every loop.
The order is as follows:
Start Loop => init => CheckCondition => if OK Progress the indexer and execute loop's body, else the loop is done.
The initialization part happens just once, if you want it to happen foreach interation it should be inside the loop or in the conditional section of the loop instead.
Best practice would be to use a while loop when the number of iterations is unknown ahead, like in this case, when it's determined by user's input.

How to end loops

Starting to learn about loops. It seems like these things go on forever because I am not telling it to stop. Problem is I don't know how to tell it to stop. I am assuming a statement such as != but I really do not know.
Anyone care to explain how loops stop?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication326
{
class Program
{
static void Main(string[] args)
{
bool triLoop = true;
while (triLoop)
{
Console.WriteLine("Please enter the first integer...");
int firstInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the second integer...");
int secondInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the third integer...");
int thirdInt = int.Parse(Console.ReadLine());
if ((firstInt + secondInt > thirdInt) && (secondInt + thirdInt > firstInt) && (firstInt + thirdInt > secondInt))
{
Console.WriteLine("The numbers {0}, {1}, and {2} CAN represent sides of the same triangle.", firstInt, secondInt, thirdInt);
}
else
{
Console.WriteLine("The numbers {0}, {1}, and {2} CANNOT represent the sides of the same triangle.", firstInt, secondInt, thirdInt);
}
}
}
}
}
The break statement will "break out" of a loop.
Alternatively, you can just set your boolean value (triLoop) to false.
Anyone care to explain how loops stop
While loop will run for as long as the condition within the loop is true. In order to break it you need to set the expression in the while loop to false.
it will stop when you set triLoop to false. You should read the documentation.
while(triLoop)
{
if(somecondition)
triLoop = false; //loop will not run after this
}
a basic example of this. This loop will run till 5.
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
Set triLoop to false. Or use break;.
Other answers have explained how the condition works, but if you want to ask the user whether they want to continue, you could add this to the end of your loop:
Console.WriteLine("Would you like to continue? (Y/N)");
if(Console.ReadLine() == "Y")
triLoop = false;
Then the condition will evaluate to false if the user types "Y", and the loop will end.
There are multiple answers.
break; //exits the loop and continues with the code
return; //stops the loop and doesn't proceed with the rest of the code
In your case, you can also set triloop to false.
use this in loops to stop loops
break;
as you are using while loop
while (triLoop)
{
}
this loop runs while triLoop variable is true
you need to set it to false somewhere within while loop
like
while (triLoop)
{
//your code
// on some condition
triLoop = false;
}
or
while (triLoop)
{
//your code
// on some condition
break;
}
try this:
while (triLoop)
{
Console.WriteLine("Please enter the first integer...");
int firstInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the second integer...");
int secondInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the third integer...");
int thirdInt = int.Parse(Console.ReadLine());
if ((firstInt + secondInt > thirdInt) && (secondInt + thirdInt > firstInt) && (firstInt + thirdInt > secondInt))
{
Console.WriteLine("The numbers {0}, {1}, and {2} CAN represent sides of the same triangle.", firstInt, secondInt, thirdInt);
}
else
{
Console.WriteLine("The numbers {0}, {1}, and {2} CANNOT represent the sides of the same triangle.", firstInt, secondInt, thirdInt);
}
Console.WriteLine("press 0 if you want to continue...");
int flag = int.Parse(Console.ReadLine());
if(flag!=0) break;
}

C# User input needs to be >= 2, but how to make it so?

This part is hard for me for some reason. Everything else works nicely, but I can't seem to figure out how to make it to where it re-asks the question if the input is >=2...
if (minimumSides >= 2)
I get this part, but it hates minimumsides >= 2.
do
{
Console.Write("Enter minimum number of sides >2: ");
int.TryParse(inputminside, out minimumSides);
if (minimumSides >= 2)
Console.Write("Enter minimum number of sides >2: ");
else
inputminside = Console.ReadLine();
}
while (!int.TryParse(inputminside, out minimumSides));
You are almost there:
do {
Console.Write("Enter minimum number of sides >2: ");
inputminside = Console.ReadLine();
} while (!int.TryParse(inputminside, out minimumSides) || minimumSides < 2);
Could the problem be that during the first iteration of the loop "inputminside" has not been initialized?
This is one way you could do it:
var minimumSides = 0;
while (minimumSides <=2)
{
Console.Write("Enter minimum number of sides >2: ");
int.TryParse(Console.ReadLine(), out minimumSides);
}
// carry on with your code here...
This is what you want -
do
{
Console.Write("Enter minimum number of sides >2: ");
inputminside = Console.ReadLine();
}
while (!int.TryParse(inputminside, out minimumSides) && minimumSides < 2);

Categories

Resources