C# Method Declaring - c#

public void GetPosNonZeroDouble()
{
double x;
Console.WriteLine("Enter The Length Of The Side");
x = double.Parse(Console.ReadLine());
if (x <= 0)
Console.WriteLine("Error - input must be a non - zero positive number");
else
return x;
x = double.Parse(Console.ReadLine());
}
static void ProcessSquare()
{
GetPosNonZeroDouble();
double side;
double answer;
Console.WriteLine();
side = double.Parse(Console.ReadLine());
answer = Math.Pow(side, 2);
Console.WriteLine("The Square Area is {0}", answer);
}
I am supposed to have a "GetPosNonZeroDouble" which needs to act like this image: c#Question
I have declared this method but am unsure how I tell processSquare() to check if the number is < 0 and how to display such by inputing the module.
Please assist me with this as i am stuck finding the solution to my problem.

You need to either make the method static, or make it part of a class and call it from an instance of the class. Also, you can't return values from a void method.
public static double GetPosNonZeroDouble()
{
double x = 0;
while (x <= 0)
{
Console.WriteLine("Enter The Length Of The Side");
if (!double.TryParse(Console.ReadLine(), x) || x <= 0)
{
Console.WriteLine("Error - input must be a non - zero positive number");
}
}
return x;
}

GetPosNonZeroDouble
Is an instance method that you are trying to call from a static method and you can't do that. You need to create an instance of whatever class GetPosNonZeroDouble is in and then invoke it using the dot notation.
Have a look here and you should also try some C# tutorials to get you going.

It seems that you don't have experience with methods in general.
As a start, I would recommend you to check the official C# documentation for methods:
https://msdn.microsoft.com/en-us/library/vstudio/ms173114(v=vs.100).aspx
For example, your method GetPosNonZeroDouble() does not return anything but you try to return a value with return x; (which would end up in a compiler error).

Related

C# read value from user console.read [duplicate]

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
Edit
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.

How to reference a variable outside of scope in C#

My professor asked us to create a program that takes in a user's height and weight, and then calculate bmi. I decided to take it a little further and added in some "input validation" logic. This means that if someone inputs "cat" for their weight, it let the user know that "cat" is not a valid weight.
class MainClass
{
public static void Main ()
{
float userWeight;
float userHeight;
bool weight = true;
Console.Write ("Weight: ");
while (weight)
{
var inputWeight = (Console.ReadLine ());
if (!float.TryParse (inputWeight, out userWeight)) {
Console.WriteLine ("Invalid input");
Console.Write ("Please try again: ");
}
else
{
weight = false;
}
}
bool height = true;
Console.Write ("Height: ");
while (height)
{
var inputHeight = (Console.ReadLine ());
if (!float.TryParse (inputHeight, out userHeight)) {
Console.WriteLine ("Invalid input");
Console.Write ("Please try again: ");
}
else
{
height = false;
}
}
float bmiHeight = userHeight * userHeight; // error for userHeight
float bmi = userWeight / bmiHeight * 703; // error for userWeight
Console.WriteLine ("You BMI is " + bmi);
}
}
The error I get is "use of unassigned local variable..". I know that I am assigning the user variables within IF statements, and that they only persist until the end of that IF statement.
My question is, how do I assign a variable in an if statement, and then reference the new value of that variable outside of that statement?
Certainly I don't have to nest them all, because that seems tedious....
The issue here is that there is a chance that your variables userHeight and userWeight are still holding garbage value since you did not initialize them.
You can try initializing them with a default valid:
float userHeight = DEFAULT_HEIGHT;
float userWeight = DEFAULT_WEIGHT;
Do ... while(condition) is more suitable for your case and also allows compiler to confirm that value is actually assigned:
var isHeightValid = false;
do
{
var inputHeight = (Console.ReadLine ());
if (!float.TryParse (inputHeight, out userHeight)) {
Console.WriteLine ("Invalid input");
Console.Write ("Please try again: ");
}
else
{
isHeightValid = false;
}
}
while (!isHeightValid);
Why: compiler is not smart enough to figure out that first iteration of while(condition) for general case will be always executed, so it assumes that code inside while may not run and hence variables will not be assigner. Yes, in your particular case it actually possible to detect that first iteration runs, but likely this is not common enough case to add rule to compiler.
do ... while on other hand guarantees that at least one iteration happens and hence variable assignment (via out parameter) will always happen from compiler's point of view.
public void heightAndWeight()
{
double height = getValue("What is your height in inches?",36,80);
double weight = getValue("What is your weight in kilograms?",45,135);
if (height > 0 && weight > 0)
{
Console.WriteLine("your BMI is " + (height * weight).ToString("N2"));
}
}
private double getValue(string question,int lowRange,int highRange) {
double ret = 0;
while(ret==0){
Console.WriteLine(question);
string retStr = Console.ReadLine();
if(double.TryParse(retStr,out ret))
{
if(ret<lowRange||ret>highRange){
Console.WriteLine("You must enter a value between "+lowRange.ToString()+" and "+highRange.ToString()+". Please try again.");
ret=0;
}else{
return ret;
}
}else{
Console.WriteLine("Invalid entry. Please try again");
}
}
return ret;
}
Why don't you want to initialize the variables with some, for example, negative value; Your code is not going to reach the end until valid values are inserted by user anyway
Fulfilling your request would defeat the purpose of local scope. It cannot be done for good reason. The point of declaring a variable locally is to not litter the broader scope with noise. In your case it isn't noise, your userWidth and userHeight variables have meaning in the main scope because you use them there. So you either initialize them properly up in the method or you declare them inside the if and move the code that uses them into the if section as well. The latter would mean you have some double code, you can fix that by moving the calculation of the BMI to a separate method and call that from within both if sections, passing your variables as arguments and getting back the BMI.
It would not be nice to put the calculation and the output statement in the same method. But that's another story.

Reading an integer from user input

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
Edit
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.

C# How to loop user input until the datatype of the input is correct?

How to make this piece of code loop asking for input from the user until int.TryParse()
is successful?
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
System.Console.WriteLine("You must enter an integer type value"); 'need to make it ask user for another input if first one was of invalid type'
}
Version of the code after the helpful answer:
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
{
Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
Console.WriteLine("The value must be of integer type");
x = temp2;
}
}
while (!int.TryParse(Console.ReadLine(), out mynum))
Console.WriteLine("Try again");
edit:
public void setX() {
Console.Write("Enter a value for X (int): ");
while (!int.TryParse(Console.ReadLine(), out x))
Console.Write("The value must be of integer type, try again: ");
}
Try this. I personally prefer to use while, but do .. while is also valid solution. The thing is that I don't really want to print error message before any input. However while has also problem with more complicated input that can't be pushed into one line. It really depends on what exactly you need. In some cases I'd even recommend to use goto even tho some people would probably track me down and slap me with a fish because of it.
Even though the question has been already marked as answered, do-while loops are much better for validating user input.
Notice your code:
Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
Console.WriteLine("The value must be of integer type");
You have the same code at top and bottom. This can be changed:
do {
Console.WriteLine("The value must be of integer type");
} while (!int.TryParse(Console.ReadLine(), out temp2));
This can help too
public int fun()
{
int Choice=0;
try
{
Choice = int.Parse(Console.ReadLine());
return choice;
}
catch (Exception)
{
return fun();
}
}
I've been wondering quite a lot, but I just figured it out!
int number;
bool check;
do
{
Console.WriteLine("Enter an integer:");
check = int.TryParse(Console.ReadLine(), out num1);
}
while (!check);
This code will loop until the user has entered an integer number. This way, the program doesn't simply report an error, but instead immediately allows the user to input again another, correct value.

Is there a good way to use Console.ReadKey for choosing between values without doing a lot of conversion between types?

Im using Console.ReadKey() to choose from a number of options that varies from time to time.
Before this initial code snippet there is a for loop that counts occurances into counter variable of type int.
The point is to use Console.ReadKey() to get an int.
int choice = ReadKey();
Console.WriteLine("");
if (choice < counter)
{
mail.to = result[counter-1].email;
}
By using the following methods
static int ReadKey()
{
ConsoleKeyInfo choice = Console.ReadKey();
char convertedchoice = choice.KeyChar;
string convertedchoice2 = convertedchoice.ToString();
int result = TryInt(convertedchoice2);
return result;
}
static int TryInt(string totry)
{
while (true)
{
int result;
if (int.TryParse(totry, out result))
{
return result;
}
Console.WriteLine("Sorry, you need to enter a number. Try again.");
}
}
I tried using ToString() but this was the way that it would let me do it in the end.
So this looks kind of inneffective to me and hence I would really appreciate some guidance as what to do differently?
Edit:
I ended up with a combination of all the good answers below. Thanks alot guys.
static int ReadKey()
{
while (true)
{
ConsoleKeyInfo choice = Console.ReadKey();
if (char.IsDigit(choice.KeyChar))
{
int answer = Convert.ToInt32(choice.KeyChar);
return answer - 48; //-48 because 0 is represented in unicode by 48 and 1 by 49 etc etc
}
Console.WriteLine("\nSorry, you need to input a number");
}
}
For a menu system with choices 0..9 this is reasonably OK. Not for reading larger numbers though.
Your whole checking logic can be made a lot easier with char.IsDigit() :
if char.IsDigit(convertedchoice)
{
int result = convertedchoice - '0'; // char1 - char2 = int, in this case in 0..9
return result;
}
else ...
You can just call Convert.ToInt32(choice.KeyChar); directly.
That would simplify it a bit.
There are lots of ways to simplify your code, but for a start try to avoid putting everything into a variable. In general, things like:
(a + b + c) / 2
are much easier to read than things like:
int A_plus_B = a + b
int A_plus_B_plus_C = A_plus_B + c
int answer = A_plus_B_plus_C / 2
With this in mind, you could write:
static int ReadKey()
{
while (true)
{
char ch = Console.ReadKey().KeyChar;
int result;
if (int.TryParse(ch.toString(), out result))
{
return result;
}
}
}

Categories