Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having this really annoying issue (I know this is basic stuff) but when I try use tryparse, I have to enter 2 values before it says integer, I want it to say integer after 1 try. (btw I have to use tryparse)
here is an example.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int results = 0;
Console.WriteLine("how old are you?");
int.TryParse (Console.ReadLine(), out results);
if (int.TryParse (Console.ReadLine(), out results))
{
Console.WriteLine("integer");
}
else
{
Console.WriteLine("not an integer");
}
Console.ReadLine();
}
}
}
Use variables for Console.ReadLine() and int.TryParse:
Console.WriteLine("how old are you?");
string input = Console.ReadLine().Trim();
bool success = int.TryParse(input, out results);
if ( success )
{
Console.WriteLine("{0} is an integer", input); // results has the correct value
}
else
{
Console.WriteLine("{0} is not an integer", input);
}
Get rid of the first redundant call to TryParse e.g.
class Program
{
static void Main(string[] args)
{
int results = 0;
Console.WriteLine("how old are you?");
//int.TryParse(Console.ReadLine(), out results); <-- remove this
if (int.TryParse (Console.ReadLine(), out results))
{
Console.WriteLine("integer");
}
else
{
Console.WriteLine("not an integer");
}
Console.ReadLine();
}
}
Int32.TryParse converts the string representation of a number to its 32-bit signed integer equivalent.
A return value indicates whether the conversion succeeded.
So you can always use it like this.
if (int.TryParse (Console.ReadLine(), out results))
{
Console.WriteLine("integer");
}
On top of the other answers you may wish to do the TryParse in a while loop so that users must enter a valid integer
while(!int.TryParse(ConsoleReadLine(), out results)
Console.WriteLine("not an integer");
ConsoleWriteLine("integer");
To better explain your current issue, you are asking the user to enter two integers, but you only ever care about the second one. The first one is assigned to results but then it is overriden the next time you call TryParse without ever being used
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm currently learning C# and I'm having troubles. I'm getting cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when I try to use !double.TryParse
static double userDouble, correctDouble;
static void someMethod() {
Console.Write(someStringOfDoubles);
while(!double.TryParse(userDouble, out _)) {
try {
userDouble= Double.Parse(Console.ReadLine());
}
catch {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
}
// checks if the userDouble is correct or not.
if (Math.Round(correctDouble, 2) == userDouble) {
Console.WriteLine("You are Correct!\n");
}
else {
Console.WriteLine("You are Incorrect.");
}
}
What should it do: Check if userDouble is a valid double and not letter(s)/word(s).
I also tried:
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
but this gives me No overload for method 'TryParse' takes 1 arguments
Any help would be much appreciated!
You need to get console value in string variable first then check it with double.TryParse(...). Try like below.
string s = Console.ReadLine();
while(!double.TryParse(s, out userDouble)) {
Console.WriteLine($"{s} is an invalid input\n\n");
s = Console.ReadLine();
}
Below attempt of yours must work without any error. But only problem you will face is it will write 0 is an invalid input for evert input because double.TryParse will set userDouble = 0 when value from Console.ReadLine() are not double.
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
I cooked this up and was wondering if there is a better way to do this.
```Console.WriteLine("Name me.");
String cn = Console.ReadLine();
Console.WriteLine($"I like this name ,{cn}, What is my funcion? ");
String fn = Console.ReadLine();
Console.WriteLine($"I will learn how to do {fn} for you.");
Console.WriteLine("I Will double any number you give me.");
int a = Convert.ToInt32(Console.ReadLine());
int b = 2;
Console.WriteLine(a * b);
```
"Best" is subjective, but there are a few problems with the code:
Any non-number string entered will throw an exception
Any decimal number string will also throw an exception.
Instead of using Convert.ToInt32, you should consider using the TryParse method instead. This method takes in a string and an out parameter that gets set to the converted value if it's successful (otherwise 0), and it returns a bool that indicates success. If we use the decimal type, we will end up with a number that has very good precision and can include decimals.
If we then create a method with a loop that uses the result of TryParse as a condition, we can loop until the user enters a correct number.
We could also allow the user to pass in a validation method, so that they can specify what the rules are for a "valid" number (i.e. if it must be greater than zero, or must be odd, etc.).
Then we might end up with something like this:
public static decimal GetDecimalFromUser(string prompt,
Func<decimal, bool> validator = null)
{
bool isValid = true;
decimal result;
do
{
if (!isValid)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid input, please try again.");
Console.ResetColor();
}
else isValid = false;
Console.Write(prompt);
} while (!decimal.TryParse(Console.ReadLine(), out result) &&
(validator == null || !validator.Invoke(result)));
return result;
}
Similarly, we can write code that prompts the user for string input. This will save us a few lines of code in our Main method, because we don't have to keep writing Console.WriteLine and Console.ReadLine:
public static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
Now we can write code where the user cannot enter invalid input! In use, the code would then look like:
string name = GetStringFromUser("Please give me a name: ");
string fn = GetStringFromUser($"I like this name, {name}. What is my function? ");
Console.WriteLine($"I will learn how to do {fn} for you.");
decimal input = GetDecimalFromUser("Please enter a number and I will double it: ");
Console.WriteLine($"{input} * 2 = {input * 2}");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
namespace comparision
{
class numbers
{
private static string comparision;
static void Main(string[] args)
{
Console.WriteLine("Enter number a:");
string a = Console.ReadLine();
Console.WriteLine("Enter number b:");
string b = Console.ReadLine();
if a > b;
Console.WriteLine("a is greater than b");
else;
Console.WriteLine("a is greater than b");
return;
}
}
}
What I have done wrong ?
If I assume I know what your end goal is, here's everything that is wrong with your program:
You can't compare strings with just a > b. At the very best this would be a lexicographical comparison, which would compare the string "2" to be "greater than" "10", because it compares it character by character.
I guess you actually meant the two things you input to be actual numbers, in which case you either want:
int a = int.Parse(Console.ReadLine()); // if integers (whole numbers)
or
double a = double.Parse(Console.ReadLine()); // if floating point
And same goes for the b variable
However, < and > are not defined for string comparison. If you actually want to do string comparison, and not numeric comparison, you could use one of the members of the StringComparer class to pick the type of string comparison, such as StringComparer.CurrentCultureIgnoreCase.Compare(a, b) which would return a number less than 0 (if a < b), greater than zero (if a > b) or equal to zero (if a == b).
The syntax for an if-statement is if (...), not if ...;
The syntax for else doesn't require a semicolon. What you've actually done is to say "else do nothing", the semicolon means "do nothing" when placed like this. You want to take that out.
As for other improvements, that aren't actual errors:
You don't need a return statement for a method that returns void, if it's the last thing you do in the method
You have no use for the static string field you've declared
The two messages you output are the same, which means the program will say the same regardless of which number is the greatest one
What happens if you input two equal numbers?
So here's one different version of your program:
namespace comparision
{
class numbers
{
static void Main(string[] args)
{
Console.WriteLine("Enter number a:");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number b:");
int b = int.Parse(Console.ReadLine());
if (a > b)
Console.WriteLine("a is greater than b");
else if (a < b)
Console.WriteLine("a is less than b");
else
Console.WriteLine("a is equal to b");
}
}
}
Ok at the beggining I think you make some mistakes. From the start conditional for if should be inside () and after it you don't use semicolon same with else. You can't compare strings like that so you need change type for a and b for example on int and Convert string input in int. Here is corrected code:
namespace comparision
{
class numbers
{
static void Main(string[] args)
{
Console.WriteLine("Enter number a:");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number b:");
int b = Convert.ToInt32(Console.ReadLine());
if (a > b)
Console.WriteLine("a is greater than b");
else
Console.WriteLine("a is not greater than b");
Console.ReadKey();
}
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Below is the code for addition of two numbers. I ask for user input and validate the same in the function - GetValidateInput(). Code is working fine, but is it correct approach to ask for user input from user-defined function or we should do this in Main() and only validate the data in user-defined function (so that this function can be reused for other validation in some other places). What is the right approach?
class Solution
{
static void Main(string[] args)
{
Console.WriteLine("Enter the First Number");
int firstNumber = GetValidateInput();
Console.WriteLine("Enter the Second Number");
int secondNumber = GetValidateInput();
int sum = SolveMeFirst(firstNumber, secondNumber);
Console.WriteLine("The Sum is {0}",sum);
Console.ReadLine();
}
static int SolveMeFirst(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
static int GetValidateInput()
{
bool isValid = false;
string number = null;
int result;
do
{
number = Console.ReadLine();
if (int.TryParse(number, out result))
isValid = true;
else
Console.WriteLine("Invalid Number, please re-enter");
} while (!isValid);
return result;
}
}
I typically try to keep the UI code separate from the business logic code, which means that, for the most part, I don't have calls to Console.ReadLine or Console.WriteLine in most methods.
Having a helper library that does input validation, however, is essential if you're doing a lot of user interaction through a Console. I have a library with methods similar to yours, only which take in the prompt to display to the user as an argument, so the method can be reused. The simplest version might look something like this:
public static int GetIntFromUser(string prompt)
{
int input;
do
{
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
Then you can call it like this:
int firstNumber = GetIntFromUser("Enter the First Number");
int secondNumber = GetIntFromUser("Enter the Second Number");
I have similar methods for different types, so I don't have to worry about data validation in my main code.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Console.WriteLine("Enter value for Monday : ");
milesMon = Console.ReadLine();
try
{
dblMon = double.Parse(milesMon);
}
catch
{
Console.WriteLine("You entered an invalid number - a default of 0 has been set");
dblMon = 0;
while (true) break;
Console.WriteLine("Enter value for Monday : ");
milesMon = Console.ReadLine();
In it's current state the code only prompts the user after they enter incorrect data the first time they do it, I would like to know how to make it so it happens every time.
-Thanks
You should use a do or while loop to keep repeating the prompt until a valid double is entered. You should also consider adding some form of exit keywords. Like if they enter "exit, quit, q" etc.. Have it terminate the app instead of loop back around. However being a console app, ctrl + c will close it regardless of what it's doing (it's the kill command) but not everyone knows that.
bool repeat = true;
var dblMilesMon = (double)0;
do
{
Console.WriteLine("Enter value for Monday : ");
var strMilesMon = Console.ReadLine();
if (!double.TryParse(strMilesMon, out dblMilesMon))
Console.WriteLine("You entered an invalid number - please enter a numeric value.")
else
repeat = false;
}while (repeat);
//do something with dblMilesMon
You can use TryParse() to convert the input string to double, it will return false if the conversion failed; based on that input you can prompt the user that whether the input is valid or not. and this will loop until the user enter Exit
string inputVal = "";
double inputDoubleVal;
while (inputVal == "Exit")
{
Console.WriteLine("Enter value for Monday : ");
inputVal = Console.ReadLine();
if (double.TryParse(inputVal, out inputDoubleVal))
{
//Process with your double value
}
else
{
Console.WriteLine("You entered an invalid number - a default of 0 has been set");
}
}
Basically you want to write a loop. While the input is invalid, prompt the user. So you should have a bool variable called valid to indicate whether the input is valid. And than a while loop like this:
while (!valid) {
//...
}
In the while loop, prompt the user. So the code looks like this:
bool valid = false;
int input = 0;
while (!valid) {
Console.WriteLine ("Prompt");
try
{
input = Convert.ToInt32 (Console.ReadLine ());
valid = true;
}
catch {}
}
Hope this helps!
You can use recursion to create your end-less loop without using a for or while.
Also, instead of a try-catch statement, better use a TryParse
Doc ref: https://msdn.microsoft.com/en-us/library/bb384043.aspx
public int readInput(){
int val = 0;
Console.WriteLine("Enter a valid int");
string enteredVal = Console.ReadLine();
bool result = int.TryParse(enteredVal, out val);
if(result)
return val;
Console.writeLine("Try again, only int values allowed");
return readInput();
}
int val = readInput();