Zamiana tekstu na liczbę, Parse i TryParse w C#
Zamiana tekstu na liczbę – Convert
Console.Write("Provide a number and I will double it: ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(number * 2);
Zamiana tekstu na liczbę – Parse
Console.Write("Provide a number and I will double it: ");
string input = Console.ReadLine();
int number = Int32.Parse(input);
int result = number * 2;
Console.WriteLine(result);
Zamiana tekstu na liczbę – TryParse
Console.Write("Provide a number and I will double it: ");
string input = Console.ReadLine();
if(Int32.TryParse(input, out int number)){
int result = number * 2;
Console.WriteLine(result);
}
else
{
Console.WriteLine("Wrong data provided.");
}
Pole powierzchni z TryParse
Console.Write("Calculate square area. Provide side a: ");
string input = Console.ReadLine();
int a;
if(Int32.TryParse(input, out a))
{
int area = a * a;
Console.WriteLine($"Square area = {area} ");
}
Program z prostym menu do obliczania pola powierzchni
Console.WriteLine("1 - Circle area");
Console.WriteLine("2 - Square area");
string menuOption = Console.ReadLine();
switch (menuOption)
{
case "1":
Console.Write("r: ");
float r;
if(float.TryParse(Console.ReadLine(), out r))
{
Console.WriteLine($"Circle area = {Math.PI * r * r}");
}
break;
case "2":
Console.Write("a: ");
float a;
if (float.TryParse(Console.ReadLine(), out a))
{
Console.WriteLine($"Square area = {a * a}");
}
break;
default:
Console.WriteLine("No option selected ");
break;
}