If we want the user to enter the data that our program will use, we need to learn a new command, which will allow us to read from the keyboard. We have "System.Console.WriteLine", but also "System.Console.ReadLine", so we would read text by doing:
myText = System.Console.ReadLine();
but that will happen in the next chapter, when we see how to handle text variables. Currently, we only know how to manipulate integer numbers, so we must convert that text to an integer, using "Convert.ToInt32":
firstNumber = System.Convert.ToInt32( System.Console.ReadLine() );
An example program to add two numbers typed by the user would be:
public class Example03
{
public static void Main()
{
int firstNumber;
int secondNumber;
int sum;
System.Console.WriteLine("Enter the first number");
firstNumber = System.Convert.ToInt32(
System.Console.ReadLine());
System.Console.WriteLine("Enter the second number");
secondNumber = System.Convert.ToInt32(
System.Console.ReadLine());
sum = firstNumber + secondNumber;
System.Console.WriteLine("The sum of {0} and {1} is {2}",
firstNumber, secondNumber, sum);
}
}
Let's make a small improvement: it is not necessary to repeat "System." at the beginning of the commands related with the system (for now, the console and conversion commands), if we use at the beginning of the program "using System":
using System;
public class Example04
{
public static void Main()
{
int firstNumber;
int secondNumber;
int sum;
Console.WriteLine("Enter the first number");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number");
secondNumber = Convert.ToInt32(Console.ReadLine());
sum = firstNumber + secondNumber;
Console.WriteLine("The sum of {0} and {1} is {2}",
firstNumber, secondNumber, sum);
}
}
Suggested exercises:
- Multiply two numbers typed by user.
- The user will type two numbers (x and y), and the program will calculate the result of their division and the remainder of that division.
- The user will type two numbers (a and b), and the program will display the result of the operation (a + b) * (a-b) and the result of the operation a2-b2.
- Sum three numbers typed by user.
- Ask the user a number and show its multiplication table. For example, if the number is 3, something like this should be written
3 x 0 = 0
3 x 1 = 3
3 x 2 = 6
…
3 x 10 = 30
No comments:
Post a Comment