this is my simple C# console app in this i will get input from user i have postal code variable in which i want to take input as integer but when i input integer it shows error. another approch is that console.readline take both int and string as input or not ??
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string firstname;
string lastname;
string birthdate;
string addressline1;
string adressline2;
string city;
string stateorprovince;
int ziporpostalcode;
string country;
ziporpostalcode =int.Parse(Console.ReadLine());
}
}
}
you should Use int.TryParse instead for int.Parse, Which is
responsible to Converts the string representation of a number to its
32-bit signed integer equivalent. A return value indicates whether the
operation succeeded, else return false(conversion failed)
So your code may looks like this:
int ziporpostalcode;
if (int.TryParse(Console.ReadLine(), out ziporpostalcode))
{
Console.WriteLine("Thank you for entering Correct ZipCode");
// now ziporpostalcode will contains the required value
// Proceed with the value
}
else {
Console.WriteLine("invalid zipCode");
}
Console.ReadKey();
Console.WriteLine("Enter Zip Code");
try
{
ziporpostalcode = int.Parse(Console.ReadLine());
Console.WriteLine("You Enter {0}", ziporpostalcode);
}
catch (Exception) {
Console.WriteLine("Error Occured, Enter only Number");
}
Console.ReadLine();
Suggested way.
Use int.TryParse to validate your input to int.
var input =int.Parse(Console.ReadLine());
if(int.TryParse(input, out ziporpostalcode )
{
// you have int zipcode here
}
else
{
// show error.
}
Related
I am trying to validate string and integer input
For string input, I am trying to implement a validation that do not accept null or integers and this is what i have for now which doesn't have error handling for integers:
string name = Console.ReadLine().ToLower();
if (name.Length == 0)
{
Console.WriteLine("Name cannot be an empty field, try again!");
name = Console.ReadLine().ToLower();
return; }
and for the integer input, I would like to only accept integers and my problem is that these codes only allow me to enter a wrong input once before it shows me an error handing exception error
Console.Write("Enter exp: ");
int exp = 0;
try
{
exp = int.Parse(Console.ReadLine());
}
catch
{
Console.Write("Invalid exp, please enter a valid numerical value!: ");
exp = int.Parse(Console.ReadLine());
}
How should I handle all these input errors or are there any improvements I can make to my codes that I have for now?
All help is greatly appreciated !
Use a while loop until the user enters an integer.
And you should never use try...catch to check if an integer can be parsed. Always use int.TryParse(...). Everything else is a code smell (and slower in the case when it is not an integer).
var integerEntered = false;
int exp;
while (!integerEntered)
{
Console.Write("Enter exp: ");
var entered = Console.ReadLine();
integerEntered = int.TryParse(entered, out exp);
if (!integerEntered)
Console.WriteLine("That was no valid integer. Please try again.");
}
Console.Write("Enter exp: ");
int exp;
bool result = int.TryParse(Console.ReadLine(), out exp)
if(result)
{
//you have an int value entered
}
else
{
Console.WriteLine("Please enter a valid number")
}
//code continues
I suggest extracting methods, e.g.
For string values input
private static string ReadString(string title,
Func<string, string> errorMessage = null) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console(title);
string input = Console.ReadLine();
string message = errorMessage == null
? null
: errorMessage(input);
if (!string.IsNullOrWhiteSpace(message))
return input;
Console.WriteLine(message);
}
}
For integer values
private static string ReadInt(string title, Func<x, string> errorMessage = null) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console(title);
string input = Console.ReadLine();
if (!int.TryParse(input, out int result)) {
Console.WriteLine("Not valid integer value. Please, try again.");
continue;
}
string message = errorMessage == null
? null
: errorMessage(result);
if (!string.IsNullOrWhiteSpace(message))
return input;
Console.WriteLine(message);
}
}
Then you can use them
string name = ReadString("Please, enter name",
v => string.IsNullOrWhiteSpace(v)
? "Name cannot be an empty field, try again!"
: "");
int exp = ReadInt("Enter exp: ", v => v < 0 ? "Exp must not be negative", "");
I have modified my code to have a function for each of your questions.
//input
get_input_func(){
string str = Console.ReadLine();
}
//validate
validation_func() {
try {
if(str.Length == 0 ) {
Console.WriteLine("Cannot be empty, please enter a num");
}
if(str.All(!Char.IsDigit)) {
Console.WriteLine("You can only enter numbers");
}
//catch multiple exceptions
catch(Exception e) {
switch(e) {
Console.WriteLine(e);
get_input_func();
}
}
Can someone help me modify my work? Help me add:
An error message when the user tries to enter decimal values.
A third operand for the calculator.
An error message when the user tries to enter any string value other than “exit”.
Here's my code:
class Program
{
static void Main(string[] args)
{
do
{
Console.Write("x = ");
string str = Console.ReadLine();
if (str == "exit")
{
Console.WriteLine("The Programme has stopped");
continue;
}
else
{
int x = Convert.ToInt32(str);
Console.Write("y = ");
int y = Convert.ToInt32(Console.ReadLine());
int sum = x / y;
Console.WriteLine("Result: {0}", sum);
}
}
while (true);
}
}
I'd be very grateful.
Here is a function you can use:
public static bool HasDecimals(decimal x) {
return Decimal.Round(x, 0) != x;
}
If I were going to do this, I'd create a function that I can use to handle most of the user interaction (emitting the prompt, parsing the input string, deciding if "Exit" was entered). In the code below, I kinda-sorta use the standard TryGetXxx pattern.
In this code below, if the TryGetDecimalValueWithPrompt returns true, then a properly parsed number is returned in the output. If it returns false, then the user has chosen to quit.
So, I start with that function:
public static bool TryGetDecimalValueWithPrompt(string prompt, out decimal outputValue)
{
while (true)
{
Console.Write(prompt + " > ");
var response = Console.ReadLine();
if (response.Equals("exit", StringComparison.OrdinalIgnoreCase) || response.Equals("quit", StringComparison.OrdinalIgnoreCase))
{
outputValue = 0.0m;
return false;
}
if (decimal.TryParse(response, out outputValue))
{
return true;
}
//otherwise, failure, so try again
Console.WriteLine("Sorry, incorrect format, try entering a correctly formatted decimal again");
}
}
The while(true) statement says Loop Forever. In this case, Forever lasts until the user has entered a properly formatted number or one of the "exit" keywords.
Then I construct my program around it:
if (!TryGetDecimalValueWithPrompt("Enter the first operand", out var operand1))
{
return;
}
if (!TryGetDecimalValueWithPrompt("Enter the second operand", out var operand2))
{
return;
}
if (operand2 == 0.0m)
{
Console.WriteLine("Sorry, you can't divide by zero");
return;
}
Console.WriteLine($"The result of op1/op2 is {operand1 / operand2}");
If you don't want to allow decimals being entered, change the TryGetDecimalValueWithPrompt function to work with integers instead:
public static bool TryGetIntValueWithPrompt(string prompt, out int outputValue)
{
while (true)
{
Console.Write(prompt + " > ");
var response = Console.ReadLine();
if (response.Equals("exit", StringComparison.OrdinalIgnoreCase) || response.Equals("quit", StringComparison.OrdinalIgnoreCase))
{
outputValue = 0;
return false;
}
if (int.TryParse(response, out outputValue))
{
return true;
}
//otherwise, failure, so try again
Console.WriteLine("Sorry, incorrect format, try entering a correctly formatted integer again");
}
}
If you work with integers, remember that integer division always yields an integer. For example, if you use integers in 7 / 2, the result will be 3, not 3.5. If you want 3.5, do something like 7 / (decimal) 2 (at that point, you are dividing an integer by a decimal and you'll get a decimal).
By the way, if you wanted to prompt for the operator (+, -, *, or /), you could create a TryGetOperator function in the same pattern and just check whatever you get from the user with something like:
var operators = new[] { "+", "-", "*", "/" };
bool goodOperator = operators.Contains(inputFromUser);
First of all, I am a complete newbie at programming and c#..so here is my dilemma.
The user should only enter a number, entering anything else should fail and repeat the question.
I have been using try catch but, as soon as the error gets thrown the user doesn't have a second chance to enter a number again, I just get an error and the ConsoleApp Closes.
This is my code atm
static public int AskInt(string question)
{
try
{
Console.Write(question);
return int.Parse(Console.ReadLine());
}
catch (Exception)
{
throw new FormatException("Please Enter a Number");
}
}
Thank you in advance.
static public int AskInt(string question)
{
int answer = 0;
bool successfullyParsed = false;
do
{
Console.Write(question);
successfullyParsed = int.TryParse(Console.ReadLine(), out var parsedAnswer);
if(!successfullyParsed){
Console.WriteLine("Only Numbers, dude");
}
answer = parsedAnswer;
} while (!successfullyParsed);
return answer;
}
Explaining a bit. TryParse will return a boolean indicating the success of the operation and an out variable with the result.
I can't return the parsedAnswer because it is in the context of the do loop.
You can make this code less legible but short. I tried to make it this why to be kinda of self explanatory.
Use below code which uses TryParse of int to parse the entered string. If TryParse succeed then it will break the while loop.
public static int AskInt(string question)
{
int questionId;
while (true)
{
Console.Write(question);
string input = Console.ReadLine();
if (int.TryParse(input , out questionId))
{
break;
}
}
}
int i=1;
while(i==1)
{
try {
Console.WriteLine("your question");
int number= int.Parse(Console.ReadLine());
i=0;
}
catch (Exception)
{
i=1;
Console.WriteLine("Please Enter a Number");
}
}
static public int AskInt(string question)
{
for (;;)
{
Console.Write(question);
if (int.TryParse(Console.ReadLine(), out int result))
{
return result;
}
}
}
This is a very simple script I am trying to figure out and I have been looking for a simple answer and can't find it in the forums or in my C# book.
Console.Write("Enter a Number\n");
int input = Convert.ToInt32(Console.ReadLine()); //convert code to an integer
if (!Int32.IsNumber(input)) //if not a whole number input give an error
{
Console.WriteLine("Not an integer");
}
It's just that simple what I'm trying to do. This is a snippet from a bigger code.
Console.Write("Enter a Number\n");
string input = Console.ReadLine(); //get the input
int num = -1;
if (!int.TryParse(input, out num))
{
Console.WriteLine("Not an integer");
}
else
{
...
}
Int.TryParse will return false if the string is not a valid integer and vise versa
I figured out the easiest and best code to get this done from many answers:
Console.Write("\nEnter a Whole Number (Such as 12)\n");
string Input = Console.ReadLine();
char firstChar = Input[0];
bool isNumber = Char.IsDigit(firstChar);
if (!isNumber)
{
Console.WriteLine("Not an integer");
}
else
{
.......
}
I wrote this method but it is giving me this error message.
"Not all code paths return a value" on GetInputstring
What do I have to do? Thanks in advance.
public string GetInputstring(string myInput)
{
int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
You have to return string from the method but you are not returning the string that is reason for getting the error. You can return the input being taking from user and stored in myInput by using return statement.
public string GetInputstring(string myInput)
{
int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput)
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
return myInput;
}
Your method does not return anything. If you are not going to return a value it should be set to void instead of public string GetInputString(string myInput) such as in the format public void GetInputString(string myInput). If you do actually want your method to return a value you must return something from each possible branch/path of your code.
In case you need some additional tips here is the MSDN documentation for the return reserved word: http://msdn.microsoft.com/en-us/library/1h3swy84.aspx