Up to now, all of your programs have been manipulating data (numbers, text, and so on) that was either fixed directly in source code or drawn from the operating system (dates, random numbers, and so on). Typically, programs get their data from the user, which is what you will learn about in this chapter.
Text Input
You will start your study of input with the simplest possible case.
Task
You will write a program that accepts a single line of text from the user and immediately repeats the inputted text to the output (see Figure 8-1).
Figure 8-1 The completed program
Solution
Here is the code:
static void Main(string[] args)
{
// Reading single line of text (until user presses Enter key)
string input = Console.ReadLine();
// Outputting the input
Console.WriteLine(input);
// Waiting for Enter
Console.ReadLine();
}
When you launch the program using the F5 key, you will see an empty screen. Enter a sentence and send it to the program using the Enter key .
Better Input
In the previous program, the user may have no idea what to do. You have not told the user what to do. In this exercise, you will improve the input procedure.
Task
You will modify the previous program in a way to give the user a hint about what she is supposed to do (see Figure 8-2).
Figure 8-2 The improved program
Solution
Here is the code:
static void Main(string[] args)
{
// Hinting user what we want from her
Console.Write("Enter a sentence (and press Enter): ");
// Reading line of text
string input = Console.ReadLine();
// Repeating to the output
Console.WriteLine("You have entered: " + input);
// Waiting for Enter
Console.ReadLine();
}
Discussion
Console.Write does not transfer the cursor to the next line, contrary to Console.WriteLine, which you have been using exclusively up to now.
Numeric Input
In previous exercises, you were engaged with the input of text information from the user. Now you will switch to numbers, which are equally important.
Task
You will write a program that takes a number from the user, stores it in a numeric variable, and finally repeats it to the user (see Figure 8-3).
Figure 8-3 Reading a number from the screen
Solution
Console.ReadLine always reads text even if its meaning is a number. If you want to hold a real number (i.e., a value of the int type), you have to manufacture it using the Convert.ToInt32 call.
static void Main(string[] args)
{
// Prompting the user
Console.Write("How old are you? ");
// Reading line of text
string input = Console.ReadLine();
// CONVERTING TO NUMBER (of entered text)
int enteredNumber = Convert.ToInt32(input);
// Output of entered number
Console.WriteLine("Your age: " + enteredNumber);
// Waiting for Enter
Console.ReadLine();
}
Discussion
Strictly speaking, you have not actually needed a real number yet since you have not made any calculation on the numbers. However, this will change in next exercise. Here you were exploring numeric input in the simplest possible form.
Calculation with Entered Number
You will now do your first calculation with the value entered by the user.
Task
You will write a program that accepts a year of birth from the user and calculates her age afterward (see Figure 8-4).
Figure 8-4 Calculating an age
Solution
Here is the solution:
static void Main(string[] args)
{
// Prompting the user
Console.Write("Enter year of your birth: ");
// Reading line of text
string input = Console.ReadLine();
// CONVERING TO NUMBER (of entered text)
int yearOfBirth = Convert.ToInt32(input);
// Finding this year
DateTime today = DateTime.Today;
int thisYear = today.Year;
// Calculating age
int age = thisYear - yearOfBirth;
// Outputting the result
Console.WriteLine("This year you are/will be: " + age);
// Waiting for Enter
Console.ReadLine();
}
Ten More
Let’s continue with the calculations .
Task
You will write a program that accepts a number from the user. After that, it displays a number that is greater by ten than the one entered (see Figure 8-5).
Figure 8-5 Adding ten to a number
Solution
Here is the code:
static void Main(string[] args)
{
// Number input
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Calculating
int result = number + 10;
// Displaying the result
Console.WriteLine("Number greater by ten: " + result);
// Waiting for Enter
Console.ReadLine();
}
Addition
You will take this step further now and make calculations with two numbers from the user.
Task
You will write a program that sums two numbers entered by the user (see Figure 8-6).
Figure 8-6 Summing two numbers
Solution
Here is the code:
static void Main(string[] args)
{
// Input of 1. number
Console.Write("Enter 1. number: ");
string input1 = Console.ReadLine();
int number1 = Convert.ToInt32(input1);
// Input of 2. number
Console.Write("Enter 2. number: ");
string input2 = Console.ReadLine();
int number2 = Convert.ToInt32(input2);
// Calculating
int result = number1 + number2;
// Result output
Console.WriteLine("Sum of entered numbers is: " + result);
// Waiting for Enter
Console.ReadLine();
}
Incorrect Input
In the previous programs with numbers, if the user entered something other than a number, the program terminated with a runtime error. Production programs, however, should not behave like this. Now you will learn how to deal with a runtime error.
Task
In this exercise, you will modify the previous program so that it correctly handles non-numeric input from the user (see Figure 8-7).
Figure 8-7 Providing feedback for an error
Solution
Leave your last project opened, or open it again if you closed it already. In what follows, you will edit the project’s Program.cs source code; specifically, you will insert a try-catch construct in an appropriate place.
Using your mouse, select the whole interior of Main excluding the last statement (waiting for Enter), exactly as shown in Figure 8-8. After that, right-click anywhere in the selected block and choose Snippet and then Surround With from context menu.
Figure 8-8 Choosing Surround With
In the small pane that pops up, select Try (see Figure 8-9).
Figure 8-9 Selecting Try
What Happened
What happened? Visual Studio wrapped the selected lines into the try block, which consists of the word try and a pair of curly brackets. It also inserted a catch block, which includes the word catch and a pair of curly brackets, after the try block.
Interior of the catch Part
Delete the statement throw inside the catch block and enter the following statement instead:
Console.WriteLine("Incorrect input - cannot calculate");
Complete Solution
Here is the complete solution:
static void Main(string[] args)
{
try
{
// Input of 1. number
Console.Write("Enter 1. number: ");
string input1 = Console.ReadLine();
int number1 = Convert.ToInt32(input1);
// Input of 2. number
Console.Write("Enter 2. number: ");
string input2 = Console.ReadLine();
int number2 = Convert.ToInt32(input2);
// Calculating
int result = number1 + number2;
// Result output
Console.WriteLine("Sum of entered numbers is: " + result);
}
catch (Exception)
{
Console.WriteLine("Incorrect input - cannot calculate");
}
// Waiting for Enter
Console.ReadLine();
}
Testing
You can test your program both for numeric input and for nonsense now.
Explanation
Statements in a try block are executed in a kind of “trial mode.”
When all of them succeed, execution in the try block proceeds normally, and the catch block is skipped afterward.
When a statement fails, the rest of the try block is skipped, and statements in the catch block are executed instead.
Summary
In this chapter, you entered a new level of programming skill. Up to now, you considered just the output from your program. Here you started dealing with the input from the user, first textual input and then numeric input.
Specifically, you learned the following:
To get text input from the user using the Console.ReadLine method call.
To display a hint to the user before requesting the input. For that purpose, you used the Console.Write method, which differs from its sister Console.WriteLine in that it does not terminate a line.
To convert textual input of a number into its actual numeric representation using the Convert.ToInt32 method to make various calculations with it afterward.
In the final exercise, you considered the important situation of runtime errors, such as non-numeric inputs, for example. You learned to deal with them using the try-catch construct. The construct consists of two blocks.
The try block surrounds statements executed “on trial.” If everything goes OK, the try block does not change anything, and after its completion, the program’s execution continues immediately after the whole try-catch construct.
The catch block surrounds statements that are executed exclusively when an error appears during the try block processing. In the presence of the catch block, a statement in the try block that fails does not cause a runtime error and program termination. Instead, the error is “caught,” and a specified alternative action is launched.