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.
Related
I created this code in c# to convert a hexadecimal number entered by the user to decimal and binary which the code does but I want the code to run so that if the user enters a letter that is not between a-f, a message box shows up with a message telling the user their input is invalid but instead of doing this, the code gives me an error. Can anyone help me out?
bool valid = false;
string hexadecimalnum = HexadecimalTxt.Text;
Checking if the number inputed by the user is in between 0-9 and a-f (lowercase or uppercase)
if(Regex.IsMatch(hexadecimalnum, "\[^-9A-F\]+$") || Regex.IsMatch(hexadecimalnum, "\[^-9a- f\]+$"))
{
// if the hex value is in between 0-9 and a-f then the condition is true
valid = true;
}
since the condition is true convert the hex number to binary and decimal
if(valid)
{
DecimalTxt.Text = Convert.ToInt32(hexadecimalnum, 16).ToString();
int temp = Convert.ToInt32(hexadecimalnum, 16);
BinaryTxt.Text = Convert.ToString(temp, 2);
}
// the condition is not true so print out a invalid number message
else
{
MessageBox.Show("Invalid - please enter a hexadecimal value in this box");
}
So, after some testing and googling, I think it's your regex pattern.
Another answer here worked: Validate hexadecimal string using regular expression
I tested the match and it worked fine.
"^(0x|0X)?[a-fA-F0-9]+$"
if you don't want the 0x, go with: "^[a-fA-F0-9]+$"
I find that using an online tester like http://regexstorm.net/tester helps.
try this solution:
if (Regex.IsMatch(s, #"\A\b[0-9a-fA-F]+\b\Z"))
{
int temp = int.Parse(hexadecimalnum, System.Globalization.NumberStyles.HexNumber);
DecimalTxt.Text= temp.ToString();
BinaryTxt.Text = Convert.ToString(temp, 2);
}
else
{
MessageBox.Show("Invalid - please enter a hexadecimal value in this box");
}
or you can use TryPrase() Int64_TryParse to check if string is valid
long temp ;
if(long.TryParse(hexadecimalnum, System.Globalization.NumberStyles.HexNumber, null, out temp))
{
DecimalTxt.Text= temp.ToString();
BinaryTxt.Text = Convert.ToString(temp, 2);
}
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());
I am creating a soundDex application and I need to ask the user for a second name after they have inputted the first one. I also want "error no input" if the user does not input a second name. How would I do this within my soundDex?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoundDexFinal
{
class Program
{
static void Main(string[] args)
{
string input = null;
bool good = false;
Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits."
+ "The program allows the user essentially to enter two names and get an encoded value.");
while (!good) // while the boolean is true
{
Console.WriteLine("Please enter a name -> "); // asks user for an input
input = Console.ReadLine();
// Make sure the user entered something
good = !string.IsNullOrEmpty(input); // if user enters a string which is null or empty
if (!good) // if boolean is true
Console.WriteLine("Error! No input."); // displays an error to the user
}
soundex soundex = new soundex(); // sets new instance variable and assigns from the method
Console.WriteLine(soundex.GetSoundex(input)); // gets the method prior to whatever the user enters
Console.ReadLine(); // reads the users input
}
class soundex
{
public string GetSoundex(string value)
{
value = value.ToUpper(); // capitalises the string
StringBuilder soundex = new StringBuilder(); // Stringbuilder holds the soundex code or digits
foreach (char ch in value) // gets the individual chars via a foreach which loops through the chars
{
if (char.IsLetter(ch))
AddChar(soundex, ch); // When a letter is found this will then add a char
} // soundex in (parameter) is for adding the soundex code or digits
return soundex.ToString(); //return the value which is then converted into a .String()
}
private void AddChar(StringBuilder soundex, char character) //encodes letter as soundex char and this then gets appended to the code
{
string code = GetSoundexValue(character);
if (soundex.Length == 0 || code != soundex[soundex.Length - 1].ToString())
soundex.Append(code);
}
private string GetSoundexValue(char ch)
{
string chString = ch.ToString();
if ("BFPV".Contains(chString)) // converts this string into a value returned as '1'
return "1";
else if ("CGJKQSXZ".Contains(chString)) // converts this string into a value returned as '2'
return "2";
else if ("DT".Contains(chString)) // converts this string into a value returned as '3'
return "3";
else if ("L".Contains(chString)) // converts this string into a value returned as '4'
return "4";
else if ("MN".Contains(chString)) // converts this string into a value returned as '5'
return "5";
else if ("R".Contains(chString)) // converts this string into a value returned as '6'
return "6";
else
return ""; // if it can't do any of these conversions then return nothing
}
}
}
}
I admit, I am not entirely clear on what part precisely you're having trouble with. But the specific goal is stated clearly enough, and you've provided a sufficient code example, so…
The basic problem is "how do I require the user to input the same kind of data more than once?" The basic answer is the same as for any programming problem that involves having to repeat an action: generalize that action into a subroutine (i.e. "method" in C# parlance) that will perform that action, and call the subroutine every time you need to perform the action.
For example:
class Program
{
static void Main(string[] args)
{
string input1, input2;
Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits."
+ "The program allows the user essentially to enter two names and get an encoded value.");
input1 = GetValidInput("Please enter a name -> ");
input2 = GetValidInput("Please enter a second name -> ");
soundex soundex = new soundex(); // sets new instance variable and assigns from the method
Console.WriteLine(soundex.GetSoundex(input1)); // gets the method prior to whatever the user enters
// do whatever you want with input2 as well
Console.ReadLine(); // reads the users input
}
static string GetValidInput(string prompt)
{
while (true)
{
string input;
Console.WriteLine(prompt); // asks user for an input
input = Console.ReadLine();
// Make sure the user entered something
if (!string.IsNullOrEmpty(input))
{
return input;
}
Console.WriteLine("Error! No input."); // displays an error to the user
}
}
}
This question already has answers here:
How can I validate console input as integers?
(10 answers)
Closed 8 years ago.
I can't figure out what to put in brackets to make my program check if the input was number. I would like to return an error if not, and restart the process. Any suggestions?
bool running = true;
Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: ");
while (running)
{
victimCount = int.Parse(Console.ReadLine());
if (/*I want victimCount only to be accepted if it's a number*/)
{
Console.Write("\nThat's an invalid entry. Enter a correct number!: ");
}
else
{
running = false;
}
}
I want victimCount only to be accepted if it's a number
You can use int.TryParse method instead. It returns boolean value that your value is a valid int or not.
string s = Console.ReadLine();
int victimCount;
if(Int32.TryParse(s, out victimCount))
{
// Your value is a valid int.
}
else
{
// Your value is not a valid int.
}
Int32.TryParse method uses NumberStyles.Integer by default. That means your string can have;
Leading CurrentCulture's sign. (PositiveSign or NegativeSign)
Leading white spaces.
Trailing white spaces
as a number stye.
Try this:
int victimcount;
bool is Num = int.TryParse(Console.ReadLine(), out victimcount);
If `isNum` is true then the input is an integer. Use this for your check. At the same time, if the parse succeeds, the parsed value gets assigned to the `victimcount` variable (0 is assigned if it fails).
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.