Validating User Input and Type - c#

I have designed an input validation loop in C#, and I would like it to be able to check for the correct input format. I'm not sure, but I think my designed loop is not checking the type of input, just what char is entered. I know I could use a try-catch block, but shouldn't you only use exceptions for exceptional situations? This is not an exceptional situation, because I expect that the user would enter an incorrect value.
Question:
Is there a way I could redesign this loop so that it checks for valid input type as well?
Code:
do
{
Console.Write("Do you wish to enter another complex number?: (Y or N)");
response = char.Parse(Console.ReadLine());
response = char.ToUpper(response);
if (response != 'Y' && response != 'N')
Console.WriteLine("You must respond Y or N!");
} while (response != 'Y' && response != 'N');

Well Console.Readline():
Reads the next line of characters from the standard input stream.
So your data will be of type System.String.
The only other checking you could do is to check that the returned string is of length 1, so you know you have input of the right format. You don't really need the char.Parse as the elements of a string are of type char.

I don't know what your original asigment is, but the example you provided can be simplyfied by just comparing strings, ie:
response = Console.ReadLine();
if (response.ToUpper() == "Y") {...}
If you want to see if the input can be cast to the type you need (for example char), you can allways do (for every value type):
char input;
bool IsValid = char.TryParse(Console.ReadLine().ToUpper(), out input);
if (IsValid)
{
Console.WriteLine("You entered the following char: " + input);
}
Hope this helps.

Another helpful check in such a situation
Checks for a null string , "" (Empty string) and trims extra white space I.E s string like this " " become this ""
if(String.IsNullOrEmpty(response.Trim() && response != 'Y' && response != 'N'))
{
Console.WriteLine("You must respond Y or N!"); }
And for the most part it is easier to use strings over char in most simple input validation situations.

Related

CultureInfo.GetCultureInfo Causing incorrect format error

Everytime when I type in z as a input it fails. I don't understand what the problem is. It get the error " System.FormatException : Input string was not in a correct format" Dsales is a interger going into the converter to get converted into dollar and cents. Whats not correct about that?
using System;
using static System.Console;
using System.Globalization;
class HomeSales
{
static void Main()
{
string response;
int dsales = 0;
int esales = 0;
int fsales = 0;
int initial;
string damount;
string eamount;
string famount;
int damounti;
int eamounti;
int famounti;
WriteLine ("Enter a salesperson initial");
response = ReadLine();
//initial = Convert.ToInt32(response);
while (response == "d" || response == "D")
{
WriteLine ("Enter Line of sale");
damount = ReadLine();
damounti = Convert.ToInt32(damount);
dsales = dsales + damounti;
}
while (response == "z" || response == "Z")
{
WriteLine("Danielle sold {0}", dsales.ToString("C", CultureInfo.GetCultureInfo("en-US")));
}
}
}
You have incorrectly programmed your console loop.
Judging from your variable declarations and strings, your code intends to record sales amounts for different salespeople, reporting the total sale amount when sale entries are done.
The FormatException comes when you type "z" after the "Enter Line of Sale" prompt.
Instead of assuming that the user will always type a valid number, add a condition to check for a valid input before attempting to parse a number. The conditional check should also include the means to exit the loop early, or to at least avoid the code that parses a numerical value.
Also, as you're dealing with values interpreted as currency, consider using the System.Decimal (decimal) structure to store values, as calculations would be more accurate.

Why is my code outputting strings multiple times in my if statement?

My code outputs the same string multiple times. For example, typing in 40 results in "Nope! Your answer is too high. Try again." twice, and it displays "your answer is too low" twice.
while (numberguess != 40.5)
{
numberguess = Console.Read();
if (numberguess < 40.5)
{
Console.WriteLine("Nope! Your answer is too low. Try again.");
}
else if (numberguess > 40.5)
{
Console.WriteLine("Nope! Your answer is too high. Try again.");
}
else if (numberguess == 40.5)
{
Console.WriteLine("Correct! Wow, I didn't really think you would figure it out!");
break;
}
}
I expect only one string to show up when typing in a number, and I want it to correspond to whether it is lower or higher than a particular number.
There are several problems with this single line:
numberguess = Console.Read();
First this returns an int, so it will never return 40.5. Also this reads one character at a time, including the ones input by the enter key, so when you type 40 and press Enter it reads '4', then '0' then '\r' and finally '\n' (converting those chars to int). That's why it displays four messages.
Instead you have to read everything typed before the Enter with Console.ReadLine() and then convert this (string) to a double. So in the end you have to do this:
numberguess = double.Parse(Console.ReadLine());
Console.Read() reads a single character as an int. If you're trying to get what the user typed before they hit enter, read the current line, and then parse an integer from it.
int.Parse(Console.ReadLine());

Checking if user input is a letter [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 5 years ago.
I'm receiving some user input through a TextBox which is then being converted to an int so it can be used in further calculations when I click the Calculate button.
I have checked to see if the TextBox is empty when the Calculate button is clicked, if it is, then a message box appears. Now I realised I need to check to make sure it is a number being input, not a letter. I'm looking for something similar to this
if(hoursInput.Text == "" || hoursInput.Text contains "a-z")
{
\\ handle error
}
else
{
\\ continue with code
}
EDIT:
The user input is converted to an int in the else block, but I do not want the function to reach this stage of converting from string to int if the user input contains letters, which is why I want to check to see if the user input contains any letters in the if block
As mentioned, use Int32.TryParse which will return a bool of whether or not the input could be parsed to an Int32. One of the parameters is an out and will become the Int32 if the input could be parsed.
See:
https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
if(hoursInput.Text == "" || !Int32.TryParse(hoursInput.Text, out number))
{
\\ handle error
}
else
{
\\ continue with code
}
You really don't need to check anything explicitly:
int aNumber;
if (!Int32.TryParse(hoursInput.Text, out aNumber)) {
// handle error
} else {
// handle `aNumber`
}

Correct use of logical operator in C#

I have the following If block that runs upon pressing a command button on a form object. This should simply check to see if any of the four mentioned text boxes are empty and if so, display a message box then exit that procedure so that the user can correct the fields and continue.
Here is the relevant code:
if (string.IsNullOrWhiteSpace(txtName.ToString()) ||
string.IsNullOrWhiteSpace(txtID.ToString()) ||
string.IsNullOrWhiteSpace(txtSalary.ToString()) ||
string.IsNullOrWhiteSpace(txtERR.ToString()))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
I've left all the text fields blank, and even tried putting white space characters in but the conditional code isn't being executed. As the code isn't executing I'm assuming there is something wrong with my if statement, perhaps I'm not using the 'or' operator || correctly? Any help appreciated.
If you are checking textboxes you need to get the text from the textbox.
if (string.IsNullOrWhiteSpace(txtName.Text) || ...
As a little bonus you could also write it like this:
if(new [] {txtName, txtID, txtSalary, txtERR}
.Any(tb => string.IsNullOrWhiteSpace(tb.Text)))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
You should use Text property of TextBox. ToString method returns string "System.Windows.Forms.TextBoxBase". This string is obviously never empty or null.
if (string.IsNullOrWhiteSpace(txtName.Text) ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
If txtName, txtID etc. name of controls then you need to refer to .Text property. Try something like snippet below:
if (string.IsNullOrWhiteSpace(txtName.Text) ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
TextBox.ToString() will return the type of the TextBox - thus this will never be NullOrWhiteSpace. What you want is to check the contents of the Text property like so:
if (string.IsNullOrWhiteSpace(txtName.Text ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
I don't use IsNullOrWhiteSpace for that kind of test, instead i prefer to use IsNullOrEmpty
try this:
if (string.IsNullOrEmpty(txtName.Text)||...)
{...
or maybe txtName is returning the TEXT object...try this then
if (string.IsNullOrEmpty(txtName.Text.toString())||...)
{...

Char tryParse not working as I thought?

I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.

Categories