How can I make a digital variable not accept the text variable - c#

back: Console.Write("The first number= ");
int x = int.Parse(Console.ReadLine());
if (x== string ) { goto back;} // here my proplem
How can I model this: Meaning if x input string goto back

Use a loop with int.TryParse that checks if the value is number and break from the loop when the Number is entered correctly.
int x;
while(true)
{
Console.Write("The first number= ");
bool success = int.TryParse(Console.ReadLine(), out x);
if (success)
break;
}
Or if you wish to use goto
int x;
back:
Console.Write("The first number= ");
bool success = int.TryParse(Console.ReadLine(), out x);
if (!success)
goto back;

Related

Input string was not in a correct format. Can't tell where's the problem

I'm trying to make a program to check if values are even or odd. And I want it to show a line of text if the user doesn't input an integer. I'm doing this with an if statement and the tryparse method.
Code:
Console.WriteLine("Please, insert a number");
string input = Console.ReadLine();
int Num = Convert.ToInt32(input);
if ( ! int.TryParse(input, out Num))
{
Console.Write("That's not even a number...");
}
else
{
Console.WriteLine("Is the number odd?");
int remainder = Num % 2;
Console.WriteLine(remainder != 0);
Console.WriteLine("\r\n");
Console.WriteLine("Is the number even?");
Console.WriteLine(remainder == 0);
Console.Read();
}
Your problem is this line:
int Num = Convert.ToInt32(input);
This is trying to convert the input to an integer before checking if it can actually be parsed as an int. If you send a into Convert.ToInt32() it will fail because a is not an int.
Remove this line, add the variable declaration in the next line (int.TryParse(input, out int Num)), and your code should work like you expect it to.

C# CMD input validation

I'm trying to make it so that when a number is entered my program will not crash, which this does so far. Then I want it to re ask for an input until the correct charcter type is enetered.
int firstNum;
int Operation = 0;
switch(Operation)
{
case 1:
bool firstNumBool = int.TryParse(Console.ReadLine(), out firstNum);
break;
}
Decompose your solution; extract a method for inputing an integer:
private static int ReadInteger(string title) {
// Keep on asking until correct input is provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value; please, try again.");
}
}
And then use it:
int firstNum;
...
switch(Operation)
{
case 1:
firstNum = ReadInteger("First number");
break;
...

c# Need help trying to put in and run two loops for the same input

I've put in a loop with Try.Parse so that if the user enters a decimal number, the program will ask them to enter another number until they put in a integer and then the program will carry on with the next part.
However what i'm struggling with is putting in another loop that makes it so that the user can only enter a number between 1 and 100, and if they don't there should be an error message that loops until they do enter this. Id like them to run at the same time and i have this one, but i want it to also check whether its in the range and i'm not sure how to do that.
I'm new to programming so I'm not great at this.
Thank you in advance!
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = int.TryParse(inputcost, out validcost);
while (!int.TryParse(inputcost, out validcost))
{
if (result == true)
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("Please Enter A Valid Integer Value");
Console.WriteLine();
inputcost = Console.ReadLine();
}
}
Your problem here is that the result variable you're looking at is only written once: outside the loop. Consider trying something like the following pseudocode (a do-while loop works exactly the same as a while loop, except it always gets executed once before the condition is checked):
bool validInput;
do
{
// If you set it true to begin with, you can set it false on any unmet conditions
// If it doesn't get set false, you've got a valid input and can exit the loop.
validInput = true;
Read input from user
Check if it's a valid integer, if not print message and validInput = false
Check if it's between 1-100, if not print message and validInput = false;
} while (!validInput);
Then if you want to tackle something more advanced, look at the continue keyword.
Try something like this.
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
if (!(valuecost >=1 && valuecost <=100))
{
Console.Write("Please enter value between 1 and 100.");
}
bool result = int.TryParse(inputcost, out validcost);
if (result == true)
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("Please Enter A Valid Integer Value");
}
}
It would be useful to use a method and do something like:
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = false;
while (!result)
{
result = checkNumber();
}
public static bool checkNumber()
{
if(inputcost < 1 || inputcost > 100)
{
Console.Write("Please Enter a valid value: ");
inputcost = Console.ReadLine();
return false;
}
else
return true;
}
Hope this helps.
string inputcost;
string inputmoney;
int validcost = 0;
int validmoney = 0;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
// only accept integers
while (!int.TryParse(inputcost, out validcost))
{
Console.Write("Please Enter An Integer Value: ");
inputcost = Console.ReadLine();
}
// valid integer input in variable validcost
bool done = false;
while (!done)
{
Console.Write("Enter an integer between 1 and 100: ");
inputmoney = Console.ReadLine();
if (int.TryParse(inputmoney, out validmoney))
{
if (validmoney > 0 && validmoney < 101)
{
done = true;
}
else
{
Console.WriteLine("Invalid input: " + inputmoney);
}
}
else
{
Console.WriteLine("Invalid input: " + inputmoney);
}
}
//validcost is an integer and validmoney is an integer between 1 and 100
Console.WriteLine("validcost: " + validcost + " validmoney: " + validmoney);
Console.ReadKey();

Validate if integer equals string

So im trying to simply check if my variable is entered as a string, I want the if statement to go through and not an unhandled exception...
Here's my code:
Console.Write("Input: ");
int i;
bool success = int.TryParse("", out i);
if (success) {
Console.WriteLine("Enter Integer!");
} else {
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Output: ", i);
}
So what am I doing wrong here? Every time I am entering a string, I'm not getting to the if statement, only a crash!
The problem in your code is that the value passed to TryParse has no connection to the value passed to Convert.ToInt32. You should read the value in, then call TryParse with the same value:
Console.WriteLine("Enter an integer:");
var s = Console.ReadLine();
int i;
if (int.TryParse(s, out i)) {
Console.WriteLine("You entered an integer");
} else {
Console.WriteLine("You did not enter an integer");
}
If you would like to continue reading until the end-user enters a valid int, add a loop, like this:
int i;
do {
Console.WriteLine("Enter an integer:");
var s = Console.ReadLine();
} while (!int.TryParse(s, out i));
I think you should do it this way
Console.Write("Input: ");
int i;
bool success = int.TryParse(Console.ReadLine(), out i); //Getting the input and checking it
if (!success)
{
Console.WriteLine("Enter Integer!");
}
else
{
Console.WriteLine("Output: ", i);
}
In your code you were getting the value in the else statement and if your input cannot be parsed to int, then exception throws.

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.

Categories

Resources