I'm building console applications to sharpen my c# skills. I'm having two issues that I can't seem to find online.
Issue 1: I want to display whatever the user inputs in the output (user enters a numeric value.. when the program runs and displays an answer, I want the user input to be displayed as well)..
Issue 2: Currently you have to press the enter key twice to continue after the first input. Is there a way to only have to press the enter key once?
Thanks in advance!
Here is the existing code (I'll include both classes just incase you need the second for some reason):
namespace StaticDemo {
class Program
{
static void Main(string[] args)
{
string selection = string.Empty;
while (selection != "q" && selection != "Q")
{
Console.Write("Enter C)elsius to Fahrentheit or F(ahrenheit to Celsius or Q(uit. \nSelect C, F, or Q then press the enter key twice to continue: ");
selection = Console.ReadLine();
double fahrenheit = 0, celsius = 0;
string line = Console.ReadLine();
switch (selection)
{
case "C":
case "c":
Console.Write("Please enter the Celsius temperature that you want converted to a Fahrenheit temperature: ");
fahrenheit = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine($"The temperature you provided in celsius: {line}, would be: {fahrenheit} in fahrentheit");
break;
case "F":
case "f":
Console.Write("Please enter the Farentheit temperature that you want converted to a Celsius temperature: ");
celsius = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine($"The temperature you provided in Fahrentheit: {line}, would be: {celsius} in celsius");
break;
case "Q":
case "q":
break;
default:
Console.WriteLine("Enter C F or a Q, Moron!");
break;
}
Console.WriteLine();
Console.WriteLine();
}
}
} }
The second class code is below if you need it for whatever reason:
namespace StaticDemo
{
class TemperatureConverter
{
public static double CelsiusToFahrenheit(string tempCelsius)
{
double celcius = double.Parse(tempCelsius);
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string tempFahrenheit)
{
double fahrenheit = double.Parse(tempFahrenheit);
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
}
This line is useless and it is the reason for the two input required to process the choice
string line = Console.ReadLine();
You have already read the selection variable two lines up.
To get the value for the temperature provided by the user, you need to get the input without passing it directly to the conversion class
Console.Write("Please enter the Celsius temperature that you want converted to a Fahrenheit temperature: ");
string input = Console.ReadLine();
fahrenheit = TemperatureConverter.CelsiusToFahrenheit(input);
Console.WriteLine($"The temperature you provided in Celsius: {input}, would be: {celsius} in Fahrenheit");
Of course the same applies to the other block of code that converts a Fahrenheit to Celsius. Notice also that I think you have inverted the message.
You are asking for the user input twice basically.
Console.Write("Enter C)elsius to Fahrentheit or F(ahrenheit to Celsius or Q(uit. \nSelect C, F, or Q then press the enter key twice to continue: ");
selection = Console.ReadLine().ToUpper();
Console.WriteLine("Please enter the temperature that you want converted: ");
string tempToConvert = Console.ReadLine();
switch (selection)
{
case "C":
fahrenheit = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine($"The temperature you provided in celsius: {tempToConvert }, would be: {fahrenheit} in fahrentheit");
break;
Consider using ToUpper or ToLower on user inputs so you don't have to worry about the formatting of the input when you make your cases.
It is because of line
string line = Console.ReadLine();
Change it to
string line;
I think you previously wanted that line to read value to convert.
Change the line
selection = Console.ReadLine();
to
selection = Convert.ToString(Console.ReadKey());
also i think after making the above change you do not need this line.
string line = Console.ReadLine();
Related
For example, lets say I have and int called input. And then I get input for it. Like this:
input = Console.ReadLine();
But when the user gets prompted, input is a string, and then it gets an error and crashes the program. How do I check if a string was entered for input?
Is there an option for it like if (input.equals(string)) or something like that?
EDIT: I tried doing the TryParse but I think I'm doing it wrong. I posted the code below
string numberOne;
string numberTwo;
double answer;
string operand;
Console.WriteLine("Enter the first number");
numberOne = Console.ReadLine();
if (double.TryParse(numberOne, out double value))
{
Convert.ToInt32(numberOne);
}
else
{
Console.WriteLine("Non integer entered. Please enter a valid number.");
}
Console.WriteLine("Enter the operator");
operand = Console.ReadLine();
Console.WriteLine("Enter the second number");
numberTwo = Console.ReadLine();
if (double.TryParse(numberTwo, out double value2))
{
Convert.ToInt32(numberTwo);
}
else
{
Console.WriteLine("Non integer entered. Please enter a valid number.");
}
switch(operand)
{
case "+":
answer = numberOne + numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "-":
answer = numberOne - numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "*":
answer = numberOne * numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "/":
answer = numberOne / numberTwo;
Console.WriteLine("The answer is " + answer);
break;
default:
Console.WriteLine("Please enter a valid operator such as +, -, *, or /");
break;
}
Console.Readline() always returns a string, however you can do this to check if an integer is inputed and continue asking for correct type of input until user delivers it.
string input = Console.ReadLine();
int parsed;
while (!int.TryParse(input, out parsed))
{
Console.WriteLine("Please enter a number!");
input = Console.ReadLine();
}
//do something with parsed
Console.ReadLine always returns a string. It's doesn't return differently typed things based the content read from console. It's your job to decide if the value entered matches your requirements (in this case it should be something that can be parsed to an int).
You can use int.TryParse to try parsing a string as int without it throwing an exception when parsing fails.
string input = Console.ReadLine();
if(int.TryParse(input, out int value))
{
// value contains an int parsed out of input
}
else
{
// parsing fails, you can do something about that, e.g. ask user for different input
}
Im trying to write a basic calculator with a main menu and sub menu.
The code is working fine when a valid entry is inputted, but I want an error message to be displayed and then return the user to the main menu when invalid data is entered.
This is what I have done so far. Can someone tell me what am I doing wrong?
static void Main(string[] args)
{
// Main method (only to be used for mainmenu() execution)
MainMenu();
}
// Main Menu method
static void MainMenu()
{
// Declaring variables
// Selection variable, used in user's input to get to the desired operation
int sel;
char letter;
// Main menu styling
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
// Converting user's input to sel's type (byte)
sel = int.Parse(Console.ReadLine());
// Processing sel
switch (sel)
{
case 1:
// Execute Addition()
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!"); //Catch
break;
}
}
static void SecondMenu()
{
char sel2; // Selection variable, used in user's input to get to the desired operation
// Display Menu Options
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
// Converting user's input to sel's type (byte)
sel2 = Convert.ToChar(Console.ReadLine());
// Processing sel
switch (sel2)
{
case 'a':
// Execute Addition()
Addition();
break;
case 's':
// Execute Substraction()
Substraction();
break;
case 'd':
// Execute Division()
Division();
break;
}
}
// Addition Method
static void Addition()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 + num2;
// Printing out the result
Console.WriteLine("RESULT: " +res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
// Substraction Method
static void Substraction()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 - num2;
// Printing out the result
Console.WriteLine("RESULT: " + res);
Console.ReadKey(true);
MainMenu();
}
// Division
static void Division()
{
// Declaring variables
double num1, num2, res;
Console.Write("Please enter the first number: ");
// Getting user's input and converting it
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
// Getting user's input and converting it
num2 = Convert.ToDouble(Console.ReadLine());
// Processing numbers into one variable
res = num1 / num2;
// Printing out the result
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
You can call the MainMenu() method in the default part of the switch in it.
switch (sel)
{
case 1:
// Execute Addition()
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format!");
MainMenu();
//Catch
break;
}
It is also recommended to have a condition to exit the program (like a maximum number of invalid inputs).
Something like this works, but you'll have to adjust accordingly to fit your requirements:
int sel;
char letter;
bool valid = false;
do
{
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
sel = int.Parse(Console.ReadLine());
switch (sel)
{
case 1:
SecondMenu();
break;
case 2:
Environment.Exit(0);
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
break;
}
}
while (valid != true);
You could just do it like this
static void SecondMenu()
{
char sel2; // Selection variable, used in user's input to get to the desired operation
// Display Menu Options
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
sel2 = Convert.ToChar(Console.ReadLine());
switch (sel2)
{
case 'a':
Calc(1);
break;
case 's':
Calc(2);
break;
case 'd':
Calc(3);
break;
default:
Console.WriteLine("Wrong entry! Try again");
MainMenu();
return;
}
}
static void Calc(int f)
{
double num1, num2, res;
try
{
Console.Write("Please enter the first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the second number: ");
num2 = Convert.ToDouble(Console.ReadLine());
switch (f)
{
case 1:
res = num1 + num2;
break;
case 2:
res = num1 - num2;
break;
case 3:
res = num1 / num2;
break;
default:
Console.WriteLine("Wrong entry! Try again");
MainMenu();
return;
}
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadKey(true);
MainMenu();
}
catch
{
Console.WriteLine("Wrong entry! Try again");
MainMenu();
}
}
EDIT: To make sure the first menu wont crash, sorround it with a try catch block
try
{
sel = int.Parse(Console.ReadLine());
switch (sel)
{
case 1:
SecondMenu();
break;
case 2:
Console.ReadLine();
break;
default:
Console.WriteLine("Sorry that is not correct format! Please restart!");
MainMenu();
break;
}
}
catch
{
Console.WriteLine("Sorry that is not correct format! Please restart!");
MainMenu();
}
Your problem was, that it tried to parse a char into an int, what is not possible.
You can either write the switch case in another method and call the main method at the default case after printing the error message,
OR
Use a do-while loop,
Inside do, write the switch cases and put a condition at while to exit the calculator.
For example: 'Enter -1 to exit the calculator' and condition in while x!=-1
Try having a play with this:
static void Main(string[] args)
{
MainMenu();
}
static void MainMenu()
{
int sel = -1;
while (sel != 2)
{
Console.WriteLine("Calculator");
Console.WriteLine("********************");
Console.WriteLine("1- Calculator");
Console.WriteLine("2- Exit Calculator");
Console.Write("Please enter your option here: ");
sel = int.Parse(Console.ReadLine());
if (sel == 1)
{
SecondMenu();
}
else if (sel != 2)
{
Console.WriteLine("Sorry that is not correct format! Please restart!"); //Catch
}
}
}
static void SecondMenu()
{
var options = new Dictionary<char, Func<double, double, double>>()
{
{ 'a', (x, y) => x + y },
{ 's', (x, y) => x - y },
{ 'd', (x, y) => x / y },
};
while (true)
{
Console.WriteLine("");
Console.WriteLine("********************");
Console.WriteLine("A. Addition");
Console.WriteLine("S. Substraction");
Console.WriteLine("D. Division");
Console.WriteLine("********************");
Console.Write("Please enter your option here: ");
char sel = Convert.ToChar(Console.ReadLine());
if (options.ContainsKey(sel))
{
Calculate(options[sel]);
break;
}
}
}
static void Calculate(Func<double, double, double> operation)
{
Console.WriteLine("Please enter the first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter the second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
double res = operation(num1, num2);
Console.WriteLine("RESULT: " + res);
Console.WriteLine("");
Console.ReadLine();
}
I am trying to create the menu for a mastermind game which can be ran in a command prompt using C#. The issue I am running into is capturing the users input for the menu. If they enter a 2 then it should display that they entered the number two and if not then it would say they have not displayed the number two.
The issue I am having is that it wont turn the users input into a working integer and will either come up saying that it can't explicitly convert from System.ConsoleKeyInfo to int or string to int.
using System;
namespace MasterMind
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
int userinput = Console.ReadKey();
if (Nuserinput == 2);
{
Console.WriteLine("This is a number 2");
}
else
{
Console.WriteLine("This is not a number 2");
}
}
}
}
Console.ReadKey() returns a ConsoleKeyInfo object, which is not an int object. You can get a char from that, for example:
var key = Console.ReadKey();
var keyChar = key.KeyChar;
If you expect that char value to represent an integer, you can convert it to one:
int keyInt = (int)Char.GetNumericValue(keyChar);
Aside from other error checking you might want to put in place in case the user doesn't enter a valid integer, this would at least get your the integer value you're looking for.
Console.ReadKey() returns a ConsoleKeyInfo, so you'll need to do something like this:
ConsoleKeyInfo data = Console.ReadKey();
int num;
if (int.TryParse(data.KeyChar.ToString(), out num) && num == 2)
{
Console.WriteLine("This is a number 2");
}else{
Console.WriteLine("This is not a number 2");
}
Change your
int userinput = Console.ReadKey();
if (Nuserinput == 2)
To:
string userInput = Console.ReadKey().KeyChar.ToString();
if(input == "2")
Or covert the string to an int as shown in other answers. But for this, a string works fine.
This is literally my first program I've ever written (started learning this past Monday); I am a total newbie.
My question is, how can I prevent exceptions from being thrown when a user enters an invalid character when the program prompts the user for fahreinheit or celsius entry (expecting a number)??? So for example, when a user enters "asfasd", the program throws an exception.
I did a lot of searching on the site before posting this, and I was successfully able to find other input validation questions, however, they were all concerning C and C++ and since I am such a newbie, I have a hard time with understanding those languages and how they relate to C#. Thank you. Please see code:
using System;
namespace Converter
{
class Program
{
static void Main()
{
float? FahrenheitInput = null;
double? CelsiusInput = null;
float? KilogramInput = null;
float? PoundsInput = null;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
FahrenheitInput = float.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
CelsiusInput = double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static float? FahrenheitToCelsius(float? INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double? CelsiusToFahrenheit(double? INPUT)
{
return INPUT * 1.8 + 32;
}
}
}
You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
class Program
{
static void Main(string[] args)
{
double FahrenheitInput = 0;
double CelsiusInput = 0;
double KilogramInput = 0;
double PoundsInput = 0;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static double FahrenheitToCelsius(double INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double CelsiusToFahrenheit(double INPUT)
{
return INPUT * 1.8 + 32;
}
}
TryParse is your good friend here. In most scenarios, you should favor using TryParse than Parse. In your example, you can do something like:
int validInt;
int.TryParse(Console.ReadLine(), out validInt);
float validFloat;
float.TryParse(Console.ReadLine(), out validFloat);
Parse vs. TryParse
The easiest way, IMHO, to change the routine is to rewrite Parse into corresponding TryParse:
// UserChoice = int.Parse(Console.ReadLine());
UserChoice = int.TryParse(Console.ReadLine(), out UserChoice) ? UserChoice : -1;
...
A bit more complex (you have to convert float into float?)
// FahrenheitInput = float.Parse(Console.ReadLine());
float v;
FahrenheitInput = float.TryParse(Console.ReadLine(), out v) ? (float?) v : null;
The same scheme for CelsiusInput
// CelsiusInput = double.Parse(Console.ReadLine());
double d;
CelsiusInput = double.TryParse(Console.ReadLine(), out v) d (double?) d : null;
The underlying mechanic of the code is
We try to parse user input TryParse(Console.ReadLine()...
If parse succeeds (and thus TryParse returns true) we just return the out (parsed value).
If parse fails (and thus TryParse returns false) we return some special a value (-1 for UserChoice or null in case of FahrenheitInput or CelsiusInput)
P.S. in the first switch you have just case 1, case 2 and case 5; however, you've put "This is not a valid entry. Please enter 1, 2, 3, 4, or 5." in the error message. It seems, that you have to either implement case 3 and case 4 in the switch or edit the error message.
Use int.TryParse instead of int.Parse and float.tryParse instead of float.Parse
While all the answers provided seem to work, the question you asked was
how can I prevent exceptions from being thrown [..]
and I just want to point out that you do this by putting the part which throws the exception in an try-catch-block. What this does is it executes the code within try until an exception is beeing thrown and then passes this exceptions as a parameter to the catch-part where you can handle it:
EXAMPLE
do
{
try
{
// the code you already have
}
catch (Exception ex)
{
Console.WriteLine("This is no valid input (" + ex.Message + ")! Try again...");
}
} while (UserChoice != 5);
Of course preventing exceptions from beeing thrown at all in the first place is the better way (as all the other answers do suggest), but this approach works as well and ist more generic in case you run into a similar problem in the future. Using switch-case-statements for error-handling is quite common practice...
I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong? I am supposed to make this console program as homework to learn about loops, but I am finding out more about other things. It is supposed to keep a running tab of salesperson's commission based a a 10% commission of each sale. Anyways, here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TubSales
{
class Program
{
static void Main(string[] args)
{
char initial;
const double COMM_INT = 0.10;
double sale, aComm = 0, bComm = 0, eComm = 0;
Console.Write("Enter 'A' for Andrea, 'B' for Brittany,\n'E' for Eric, or 'Z' to quit >> ");
initial = Convert.ToChar(Console.Read());
while (initial != 'z' && initial != 'Z')
{
switch (initial)
{
case 'a':
case 'A':
Console.Write("Enter the sales for Andrea >> ");
sale = Convert.ToDouble(Console.ReadLine());
aComm = aComm + COMM_INT * sale;
break;
case 'b':
case 'B':
Console.Write("Enter the sales for Brittany >> ");
sale = Convert.ToDouble(Console.ReadLine());
bComm = bComm + COMM_INT * sale;
break;
case 'e':
case 'E':
Console.Write("Enter the sales for Eric >> ");
sale = Convert.ToDouble(Console.ReadLine());
eComm = eComm + COMM_INT * sale;
break;
default:
Console.WriteLine("You did not enter a valid initial");
break;
}
Console.Write("Enter 'A' for Andrea, 'B' for Brittany, or 'E' for Eric >> ");
initial = (char)Console.Read();
}
Console.WriteLine("Andrea had {0}, Brittany had {1}, and Eric had {2} in commissions.", aComm.ToString("C"), bComm.ToString("C"), eComm.ToString("C"));
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
}
}
I keep getting a FormatException in each of the cases on the line where I try to assign the value for the sale variable. Anyone know what I am doing wrong?
The Convert.ToDouble method will raise a FormatException if the string (returned from Console.ReadLine()) is not a valid number.
Typically, if you want to parse user input, it's a better idea to use Double.TryParse instead, as this lets you determine whether the input was a valid number without catching the exception.
This would normally look something like:
Console.Write("Enter the sales for Andrea >> ");
while (!double.TryParse(Console.ReadLine(), out sale))
{
Console.WriteLine("Value entered was not a valid number.");
Console.Write("Enter the sales for Andrea >> ");
}
// Once you get here, "sale" will be set appropriately
While Reed's answers is great, it's not the problem here.
What really happens is the same situation as this one
Console.Read only read the "Second part of the carriage return" and returns "". This is why the Convert fails.
replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine());
Replace
initial = Convert.ToChar(Console.Read());
with
initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());