I'm a beginner who is learning .NET.
I tried parsing my integer in console readline but it shows a format exception.
My code:
using System;
namespace inputoutput
{
class Program
{
static void Main()
{
string firstname;
string lastname;
// int age = int.Parse(Console.ReadLine());
int age = Convert.ToInt32(Console.ReadLine());
firstname = Console.ReadLine();
lastname=Console.ReadLine();
Console.WriteLine("hello your firstname is {0} Your lastname is {1} Age: {2}",
firstname, lastname, age);
}
}
}
If it's throwing a format exception then that means the input isn't able to be parsed as an int. You can check for this more effectively with something like int.TryParse(). For example:
int age = 0;
string ageInput = Console.ReadLine();
if (!int.TryParse(ageInput, out age))
{
// Parsing failed, handle the error however you like
}
// If parsing failed, age will still be 0 here.
// If it succeeded, age will be the expected int value.
Your code is absolutely correct but your input may not be integer so you are getting the errors.
Try to use the conversion code in try catch block or use int.TryParse instead.
You can handle invalid formats except integer like this;
int age;
string ageStr = Console.ReadLine();
if (!int.TryParse(ageStr, out age))
{
Console.WriteLine("Please enter valid input for age ! ");
return;
}
You can convert numeric input string to integer (your code is correct):
int age = Convert.ToInt32(Console.ReadLine());
If you would handle text input try this:
int.TryParse(Console.ReadLine(), out var age);
Related
I'm very new to programming and I was wondering how could I break out the loop if the number is valid with a ternary operator? I'm used to do it with if-else but in this case I don't know the proper syntax to do it or if it is possible.
Thanks!
while (!valid)
{
.....
Console.Write("Enter your phone number : ");
string noTelephone = Console.ReadLine();
string message = ValiderTelephone(noTelephone) ? "Numéro valide" : "Numéro invalide";
}
I'd go the way that Magnetron indicated in the comments if you're desperate for something that uses a ternary, but realistically there isn't any point in arranging the code lol you have/setting the message if you're going to loop until it's valid, because you don't use the message you set! This means that by the time the code reaches a point where message could be used for something, it must surely be "Number valid"
How about:
Console.WriteLine("Enter number:");
string num = Console.ReadLine();
while(!ValidNumber(num)){
Console.WriteLine("Invalid number, try again:");
num = Console.ReadLine();
}
string message = "Number valid";
Or better:
private string Ask(string question){
Console.WriteLine(question);
return Console.ReadLine();
}
...
string num = Ask("Enter number:");
while(!ValidNumber(num))
num = Ask("Invalid number, try again:");
Beginner at C# and working on a Console Application currently. If I say ask the user to type in a date but they type in a string that cannot be converted to a date time how can I ensure they're requested to try again? I know this is easy via an if/else statement but if an application has hundreds of questions like this it does not seem right to have equally hundreds of if statements just to see if the datatype is correct. Is there something in built I've missed or a "hack" to carry out this?
e.g
Console.WriteLine("What is your birthday");
Datetime bday = Convert.ToDateTime(Console.ReadLine());
User enters say "dfio".
You could write a function like
public static int GetInt()
{
int X;
String Result = Console.ReadLine();
while(!Int32.TryParse(Result, out X))
{
Console.WriteLine("Not a valid Int, try again!");
Result = Console.ReadLine();
}
return X;
}
and use it multiple times.
In your case (DateTime) you only need to change the code to
public static DateTime GetDateTime()
{
DateTime X;
String Result = Console.ReadLine();
while(!DateTime.TryParse(Result, out X))
{
Console.WriteLine("Not a valid DateTime, try again!");
Result = Console.ReadLine();
}
return X;
}
bool valid = false;
DateTime bday;
while(!valid){
Console.WriteLine("What is your birthday");
string input = Console.ReadLine();
if (DateTime.TryParse(input, out bday))
{
Console.WriteLine("Invalid Date");
valid = true;
}
}
This will loop until a valid DateTime is entered.
This documentation page will help you supply a custom format to the parser.
This is only a solution to this specific input.
Use ToString() method to take input as string.
Datetime bday = Convert.ToDateTime(Console.ReadLine().ToString());
How would I parse an empty string? int.Parse(Textbox1.text) gives me an error:
Input string was not in a correct format.
System.FormatException: Input string was not in a correct format.
If the text is empty (Textbox1.text = ''), it throws this error. I understand this error but not sure how to correct this.
If you're looking to default to 0 on an empty textbox (and throw an exception on poorly formatted input):
int i = string.IsNullOrEmpty(Textbox1.Text) ? 0 : int.Parse(Textbox1.Text);
If you're looking to default to 0 with any poorly formatted input:
int i;
if (!int.TryParse(Textbox1.Text, out i)) i = 0;
Well, what do you want the result to be? If you just want to validate input, use int.TryParse instead:
int result;
if (int.TryParse(Textbox1.Text, out result)) {
// Valid input, do something with it.
} else {
// Not a number, do something else with it.
}
if(!String.IsNullOrEmpty(Textbox1.text))
var number = int.Parse(Textbox1.text);
Or even better:
int number;
int.TryParse(Textbox1.Text, out number);
Try this:
int number;
if (int.TryParse(TextBox1.Text, out number))
{
//Some action if input string is correct
}
If the input is a number or an empty string this will work. It will return zero if the string is empty or else it will return the actual number.
int.Parse("0"+Textbox1.Text)
You could also use an extension method like this:
public static int? ToNullableInt32(this string s)
{
int i;
if (Int32.TryParse(s, out i)) return i;
return null;
}
Here's the reference: How to parse a string into a nullable int in C# (.NET 3.5)
you can wrap it with simple try/catch...
How to fix the errors with characters in C# Employee class I am making. I know how to handle string, int, and double. The char.Parse doesn't cooperate.
public static string AskForLastName()
{
string inValue;
Console.Write("Enter last name: ");
inValue = Console.ReadLine();
return inValue; //works fine
}
public static char AskForGender()
{
char inValue;
Console.Write("Enter gender: ");
inValue = Console.ReadLine();//error here for some reason
return (char.Parse(inValue));//error here for some reason
}
public static int AskForNoDependendents()
{
string inValue;
Console.Write("Enter the dependents: ");
inValue = Console.ReadLine();
return (int.Parse(inValue));//works fine
}
public static double AskForAnnualSalary()
{
string inValue;
Console.Write("Enter annual salary: ");
inValue = Console.ReadLine();
return (double.Parse(inValue));//works fine
}
Console.ReadLine() returns a string. You can't implicitly convert that to a character- what if someone enters "Male" or " M" (preceded by one or more spaces).
Your AskForGender method is going to need to be smarter about what input it accepts, and how it parses that input.
If you really need a character out of this (to satisfy the assignment, or whatever), then you need to figure out a way to get from all of the possible String inputs ("Male", "MALE", "Female", "Horse", "Dog", "4", etc.) to either:
An acceptable Character (presumably 'M' or 'F', but maybe others?)
or
An error condition, whereupon maybe you print a nice error message and ask them to re-enter?
Description
Console.ReadLine returns a string. You can use string[] to get the first character of your string. But you have to make sure that the user inserts at least one character.
Sample
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue[0] == 'm' || inValue[0] == 'w'))
return inValue[0];
}
}
Update
My sample covers now that the user inputs m or w.
Update
It is homework so...
If your Teacher ask "But what happens if the user inputs a M instead of m? You should say "It asks the user again".
If your Teacher asks then "How to make it possible to accept M and m? You should say i can make it case insensitive.
Sample
You should use i can use .NET's .ToUpper() method.
.ToUpper() - Returns a copy of this string converted to uppercase.
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue.ToUpper()[0] == 'M' || inValue.ToUpper()[0] == 'W'))
return inValue.ToUpper()[0]; // returns M or W
}
}
You're trying to pull a string into a char. Console.ReadLine() returns a string.
If you need specifically one character (Presumably M or F) consider making your inValue a string, trimming it (to ensure there are no leading spaces), and then returning inValue[0] (which should be a char)
Something like:
string inValue = Console.ReadLine();
inValue = inValue.Trim();
return inValue[0];
**Note- that's not the best way to do it, but it should make the idea fairly clear.
According to MSDN ReadLine returns a string - you can't assign a string to a char!
I'm really new to all of this. I need to write an exe application in C#. What i need to do is to be able to pass values through the console into a function. But I'm unsure as to how I can store the values that are entered through the console...
I know we can use Read() to read what has been entered but, when I'm dealing with multiple values how do i do this?
Any help will be greatly appreciated!! Thanks in advance
You start with choosing the Console Application template (in New Project)
And then, in the Main function, you can read a line at a time with
string line = Console.ReadLine();
This probably shifts your question to : How do I get values from a string?
If you have a single int at a time, it is
int x = int.Parse(line);
Are you referring to passing command line parameters to a console application? If so, there is a string array parameter (e.g. args) that holds them. See this code.
static void Main(string[] args)
{
}
You can also use Environment.GetCommandLineArgs.
Hmm I think he is wondering how to repeatitly read some value and pass it to a function.
For that you can use a simple while loop.
string data = Console.ReadLine();
do {
dummyFunction(data);
data = Console.ReadLine();
} while (data != "");
You want to programmatically compile text into code? If so you should read this KB entry from Microsoft. How to programmatically compile code using C# compiler
Or if you want to get input from the user in the console, you should use Console.ReadLine().
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
Console.Write("Hello {0}, you are {1} years old.", name, age);
You can basically do a parsing work manually. For example, if the input is a name follows by age.
Natthawut 22
You can use Console.ReadLine() to get the string "Nattawut 22". And then use String.Split(' '); to get an array of {"Natthawut","22"}. Then convert the second element to integer using Convert.ToInt32(val);
I believe there must be a better way to do this but this is how I usually do it :)
int year, month, day;
Console.WriteLine("Please enter your birth year : ");
year = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter your birth month : ");
month = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter your birth day : ");
day = int.Parse(Console.ReadLine());
Console.Write("You are ");
Console.Write(CalculateAge(year, month, day));
Console.Write(" years old.");
An alternative way is this:
Console.WriteLine("Please enter your birthday in the format YY-MM-DD : ");
string line = Console.ReadLine();
string[] parts = line.Split(new char[] { '-' });
int age = CalculateAge(parts[0],parts[1],parts[2]);
Console.WriteLine("You are {0} years old.", age);
And -PLEASE- do some input checking.