Error message not being displayed; incorrect conversion - c#

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: ");
}

Related

Ternary operator in a while loop in C#

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:");

How to print Text and value from integer on the same line in the console?

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)

c# Script Error "Line3 is a' variable' but is used like a method - Help Understand

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);
...

Unhandled Exception: System.FormatException: Input string was not in a correct format

I'm trying to get this small movie ratings program to work properly with everything going fine until I start prompting for the ratings that the reviewer would enter. It lets me rate both acting fine but as soon as I hit the enter button to rate music is will move down to a blank line instead of prompting for the next input. The only way I to get around this seems for me to enter the value twice.
thanks
Console.WriteLine("Rate the following out of 5");
Console.Write("Acting > ");
acting_rating = int.Parse(Console.ReadLine());
Console.Write("Music > ");
Console.ReadLine();
music_rating = int.Parse(Console.ReadLine());
Console.Write("Cinematography > ");
Console.ReadLine();
cinematography_rating = int.Parse(Console.ReadLine());
Console.Write("Plot > ");
Console.ReadLine();
plot_rating = int.Parse(Console.ReadLine());
Console.Write("Duration > ");
Console.ReadLine();
duration_rating = int.Parse(Console.ReadLine());
you call Console.ReadLine(); one time too often... just remove the Console.ReadLine(); between Console.Write and the int.Parse .
Although IF the user enters anthing wrong - like a word instead of a number - you will still get an exception... To handle that properly use a try catch block and/or TryParse.
Excluding Acting, you have always two Console.ReadLine(); i.e. :
Console.Write("Music > "); // write Music >
Console.ReadLine(); // read the user input (and throw it away)
music_rating = int.Parse(Console.ReadLine()); // read the user input again and parse it
Remove the single statement Console.ReadLine(); and should be ok.

Writing an executable function in C#

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.

Categories

Resources