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
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:");
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 would like to ask the user for his/her weight; for example;
Console.Write("Please enter your weight: {I want it to be inserted here} kg");
Here the input will be inserted after the kg, although I want it to be just before "kg" so that the user may know that a kg value is being expected, and that further details are not necessary (such as kg/lbs..)
Thanks in advance.
You will have to read every single key the user inputs and then set the cursorposition to the location you want the users weight to be displayed. Afterwards you write it to the console.
static void Main(string[] args)
{
string prompt = "Please enter your weight: ";
Console.Write(prompt + " kg");
ConsoleKeyInfo keyInfo;
string weightInput = string.Empty;
while ((keyInfo = Console.ReadKey()).Key != ConsoleKey.Enter)
{
//set position of the cursor to the point where the user inputs wight
Console.SetCursorPosition(prompt.Length, 0);
//if a wrong value is entered the user can remove it
if (keyInfo.Key.Equals(ConsoleKey.Backspace) && weightInput.Length > 0)
{
weightInput = weightInput.Substring(0, weightInput.Length - 1);
}
else
{
//append typed char to the input before writing it
weightInput += keyInfo.KeyChar.ToString();
}
Console.Write(weightInput + " kg ");
}
//process weightInput here
}
I've found a simple answer:
Console.Write("enter weight = kg");
Console.SetCursorPosition(0, 8);
metric.weightKgs = byte.Parse(Console.ReadLine());
It all comes down to cursor positioning and playing around with it finding the exact location.
You need to write to the console your question (I would do it like this)
Console.WriteLine("Please enter your weight (kg):");
Then wait for the value to come back.
This will wait for the user
string userInput = Console.ReadLine();
Using a dollar sign on a string allows for string interpolation. Depending on your version of C#, this may not work.
Console.WriteLine($"Your weight is {userInput}kg.");
int weight = Console.ReadLine();
if (weight != null)
Console.WriteLine(string.format("Please enter your weight: {1} kg", weight));
This is unchecked code. But should be something like that.
This is what I do, but it didn't work:
int money;
Console.Writeline("Enter how much money you want";
money=int.Parse(Console.ReadLine());
Console.Writeline("The Money you have now are",money)
You have several options:
Concatenate the strings:
Console.Writeline("The Money you have now are" + money);
Use the format specifier version of Console.WriteLine:
Console.Writeline("The Money you have now are: {0}", money);
Use Console.Write instead:
Console.Write("The Money you have now are: ");
Console.Writeline(money);
Note:
Your code doesn't actually compile due to some missing parentheses, semi-colons and incorrect casing. I would write your code as this:
Console.WriteLine("Enter how much money you want");
int money = int.Parse(Console.ReadLine());
Console.WriteLine("The Money you have now is {0}", money);
As of C# 6, this can be written as:
Console.Writeline($"The Money you have now are: {money}");
See: $ - string interpolation (C# reference)
EDIT - Thank You Grant & Tim for the previous answer, however it doesn't look like my current code was able to turn the output into decimal form. How can i make the input of the user display as a decimal?
Console.WriteLine("*************** Get Mileage***************");
Console.WriteLine("");
Console.WriteLine("Enter the Gas Mileage:");
line3 = Console.ReadLine();
if (int.TryParse(line3, out val))
{
double mileage = Convert.ToDouble(line3());
Console.WriteLine("Your car MPG is: " + mileage.ToString());
Console.WriteLine();
Console.WriteLine("");
Console.WriteLine("*************** Program Termination***************");
Console.WriteLine("");
Console.WriteLine("Thank you. Press any key to terminate the program...");
}
else
{
Console.WriteLine("Please only enter a interger, Please Close and try again");
Console.ReadLine();
}
You've got a typo on this line:
Convert.ToDouble(line3());
By typing line3(), it suggests that line3 is a method you're trying to call.
Remove the extra parentheses:
Convert.ToDouble(line3);
Why are you doing an int.TryParse on line3, and then on the next line converting it to a double?
Just try parsing it as a double to start with, then use that parsed value:
double mpg;
if (double.TryParse(line3, out mpg))
{
Console.WriteLine("Your car MPG is: " + mpg);
...