I want to read a double value and a integer value from a console application in C#. `
int ch = Console.Read();
Console.WriteLine("Enter a random integer");
int x = int.Parse(Console.ReadLine());
switch (ch)
{
case 1:
TempServiceRef.Service1Client s1 = new ConsoleTempApplication.TempServiceRef.Service1Client();
Console.WriteLine("Enter temperature");
string n = Console.ReadLine();
int param = int.Parse(n);
double result = s1.c2f(param);
Console.WriteLine(result);
Console.ReadLine();
break;
case 2:
TempServiceRef.Service1Client s2 = new ConsoleTempApplication.TempServiceRef.Service1Client();
Console.WriteLine("Enter temperature");
int param1 = int.Parse(Console.ReadLine());
double result1 = s2.f2c(param1);
Console.WriteLine(result1);
Console.ReadLine();
break;
default:
Environment.Exit(0);
break;
}
`
The console application closes once I try to enter my value for ch. Sometimes it closes after I give a value for temperature. I tried using tryParse and Convert.toInt. But I am not getting any results. Anyone who can help me with this? Further...I am just expecting the user to input only integer values(as an assumption). The tryparse usage in this case is not mandatory right?
Problem 1: You are using the
Console.Read()
method to read the single character from console.but here you need to press theEnter key
to return the entered value/character as you are using theConsole.Read()
method.so when you press the EnterConsole.ReadLine()
method will get the value Empty string and int.Parse() throws Exception on Empty Strings.Solution 1: you need to add
Console.ReadLine()
after theConsole.Read()
method to read the first character. and then you can proceed.Try This:
Problem 2: You are tryig to compare the Characters entered from console to numbers directly which does not work as when you read the character from console it will store its ASCII value not direct integer.for example if you enter
1
from console, it will be stored as49
in integer variablech
(ACII code of 1 is 49) so when you compare with 1 it does not match .Solution 2: so you need to match with its character value. so enclose the values within single quotes to match with exact value entered in console.
Try This: enclose 1 and 2 within single quotes
Complete Code: