Add and subtract
Add and test the addition and subtraction methods.
Reading input with Console
In a C# console app you read user input with Console.ReadLine(). This method returns a string; to do numerical work you must convert that string to a number.
The double.Parse method converts a string to a double. For example, double.Parse("25") returns 25.0. If conversion fails it throws FormatException; we'll cover that in the final lesson.
Type conversion and error risk
double.Parse expects a valid number format. If the user enters a value like "hello", the method throws FormatException and program flow stops.
To catch these errors you use a try/catch block. You write the risky operation inside try and handle the error inside catch. This lesson only introduces the concept; the full pattern comes in the final lesson.
Exercise Read input and convert it to a number
Inside Main, declare a string variable and assign "25" (in a real app this value comes from Console.ReadLine()). Then convert it to double with double.Parse and print it with Console.WriteLine.
Show example solution
Convert the string with double.Parse and print with WriteLine.
Example solution:
using System;
class Calculator
{
public double Add(double a, double b) { return 0; }
public double Subtract(double a, double b) { return 0; }
public double Multiply(double a, double b) { return 0; }
public double Divide(double a, double b) { return 0; }
}
class Program
{
static void Main()
{
// In a real app this comes from Console.ReadLine
string input = "25";
double number = double.Parse(input);
Console.WriteLine(number);
}
}
Test yourself
-
What type does Console.ReadLine() return?
- int
- double
- string
- char
Show answer
string — Correct; Console.ReadLine returns a string.
-
Convert the string to a number
string input = "25"; double number = ____; Console.WriteLine(number);Show answer
string input = "25"; double number = double.Parse(input); Console.WriteLine(number); -
Match each method or concept to its meaning
- Console.ReadLine
- Reads a line from the user
- double.Parse
- Converts a string to a number
- Console.WriteLine
- Writes text to the screen
- FormatException
- Invalid number format