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:");
Related
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput = Convert.ToInt32(userInput);
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
Can someone explain to me why my error message isn't showing up, and why the int newUserInput line is getting the error that it's not formatted correctly?
Try this:
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput;
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
Just do your work here int.TryParse(userInput, out newUserInput), not converting it before TryParse
It totally depends on what are you sending in with Console.ReadLine()
Also, see following:
Convert.ToInt32 will throw FormatException if input is not correct for Int32. Refer Convert.Int32(MSDN)
Also it looks like you are overwriting the Convert.Int32 again with TryParse. You actually dont need Convert.Int32
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput; //dont assign anything
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
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);
We are currently learning about functions, parameters, arguments in a class, so I want to keep the same format since 'decimal price' and 'decimal amount' will be inputed into a function definition
I have tried different ways to turn the 'decimal' into a 'string' to be able to prevent the user from entering characters instead of a decimal, but I don't know why it isn't working
Since 'amount' is a decimal, it needs to be converted into a string to be able to run (amount == string.Empty), but as the first problem I cannot figure it out.
decimal price;
decimal amount;
Console.Write("What is the price?");
price = decimal.Parse(Console.ReadLine());
double pricenumber;
while (!double.TryParse(price, out pricenumber)) //error here
{
Console.WriteLine("You've not entered a price.\r\nPlease enter a price");
price = decimal.Parse(Console.ReadLine());
}
Console.Write("How many were you planning on purchasing?");
amount = decimal.Parse(Console.ReadLine());
while (amount == string.Empty) //error here
{
Console.WriteLine("You cannot leave this blank.\r\nPlease enter how many are needed:");
amount = decimal.Parse(Console.ReadLine());
}
There are some logical flaws in your code, which you'll have to fix. Please see the comments:
Console.Write("What is the price?");
price = decimal.Parse(Console.ReadLine()); // you're already parsing the user-input into
// a decimal. This is somewhat problematic, because if the user enters "foo" instead
// of "123" the attempt to parse the input will fail
double pricenumber;
while (!double.TryParse(price, out pricenumber)) // the variable "price" already contains
// a parsed decimal. That's what you did some lines above. "TryParse" expects a string to
// be parsed whereas you're committing the parsed decimal
{
Console.WriteLine("You've not entered a price.\r\nPlease enter a price");
price = decimal.Parse(Console.ReadLine());
}
So what you should do instead is keeping the user-input as a string until you're then trying to parse it:
Console.Write("What is the price?");
string input = Console.ReadLine(); // keep as string
double pricenumber;
while (!decimal.TryParse(input, out pricenumber))
{
Console.WriteLine("You've not entered a price.\r\nPlease enter a price");
input = Console.ReadLine();
}
The same goes for your other attempt. Again, please look at the comments:
Console.Write("How many were you planning on purchasing?");
amount = decimal.Parse(Console.ReadLine()); // you're already parsing the string into a
// decimal
while (amount == string.Empty) // as you can't compare a decimal with a string, this
// creates an error
{
Console.WriteLine("You cannot leave this blank.\r\nPlease enter how many are needed:");
amount = decimal.Parse(Console.ReadLine());
}
You could solve it the same way as above:
Console.Write("How many were you planning on purchasing?");
input = Console.ReadLine(); // again, keep as string
while (!decimal.TryParse(input, out amount))
{
Console.WriteLine("You cannot leave this blank.\r\nPlease enter how many are needed:");
input = Console.ReadLine();
}
If there's room for further optimization you could and should put that logic into a separate method as the code is nearly identically and would lead to duplicates.
private static decimal GetParsedInput(string question, string noticeOnFailed)
{
Console.Write(question);
input = Console.ReadLine();
decimal result;
while (!decimal.TryParse(input, out result))
{
Console.WriteLine(questionOnFailed);
input = Console.ReadLine();
}
return result;
}
Usage:
decimal price = GetParsedInput(
"What is the price?",
"You've not entered a price.\r\nPlease enter a price:");
decimal amount = GetParsedInput(
"How many were you planning on purchasing?",
"You cannot leave this blank.\r\nPlease enter how many are needed:");
Try this:
string price;
string amount;
Console.Write("What is the price?");
price = Console.ReadLine();
double pricenumber;
while (!double.TryParse(price, out pricenumber))
{
Console.WriteLine("You've not entered a price.\r\nPlease enter a price");
price = Console.ReadLine();
}
Console.Write("How many were you planning on purchasing?");
double amountnumber;
amount = Console.ReadLine();
while (!double.TryParse(amount, out amountnumber))
{
Console.WriteLine("You cannot leave this blank.\r\nPlease enter how many are needed:");
amount = Console.ReadLine();
}
I figured it out
I've done this instead
{ public static decimal questions(string question)
{
Console.Write(question);
string answer = Console.ReadLine();
decimal result;
while (!decimal.TryParse(answer, out result))
{
Console.WriteLine(question);
answer = Console.ReadLine();
}
return result;
}
Usage:
string productcost = "How much does one " + productname + " cost? ";
questions(productcost);
worked perfectly
I need to get a short data type value as a input in C# Console Application. I heard that, its easy to get input in int, string,etc in C#. But I have to get a short data type value as a input. Please help me.
Thanks !!
string input = Console.ReadLine();
short s;
if(short.TryParse(input, out s))
{
//use s
}
else
{
//invalid input
}
Var Input = Console.ReadLine();
Short ShortInput;
Int16.TryParse(Input,out ShortInput);
You can use Console.ReadLine() and apply check on it that if given value is not short then you ask for input again.
string inputForShort = Console.ReadLine();
short result=0;
bool shortGiven = false;
do {
Console.WriteLine("Please enter short value");
inputForShort = Console.ReadLine();
shortGiven = short.TryParse(inputForShort , out result);
} while (!shortGiven);
Console.WriteLine("You entered short value" + result);
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!