View
61.128
Download
4
Category
Tags:
Preview:
DESCRIPTION
What is Console? Printing to the Console – Printing Numbers, Strings, etc. Reading from the Console – Reading Numbers and Strings Exercises: Printing and Reading form the Console
Citation preview
Console Input / Console Input / OutputOutput
Reading and Writing to the ConsoleReading and Writing to the Console
Svetlin NakovSvetlin NakovTelerik Telerik
CorporationCorporationwww.telerik.com
Table of ContentsTable of Contents
Printing to the ConsolePrinting to the Console Printing Strings and Numbers Printing Strings and Numbers
Reading from the ConsoleReading from the Console Reading CharactersReading Characters Reading StringsReading Strings Parsing Strings to Numeral TypesParsing Strings to Numeral Types Reading Numeral TypesReading Numeral Types
Various ExamplesVarious Examples
2
Printing to the Printing to the ConsoleConsolePrinting Strings, Numeral Types and Printing Strings, Numeral Types and
ExpressionsExpressions
3
Printing to the ConsolePrinting to the Console
Console is used to display Console is used to display information in a text windowinformation in a text window
Can display different values:Can display different values: StringsStrings Numeral typesNumeral types All primitiveAll primitive datadata typestypes
To print to the console use the To print to the console use the class class ConsoleConsole ( (System.ConsoleSystem.Console))
4
The Console ClassThe Console Class Provides methods for console input and Provides methods for console input and
outputoutput InputInput
Read(…)Read(…) – reads a single character – reads a single character
ReadKey(…)ReadKey(…) – reads a combination of keys– reads a combination of keys
ReadLine(…)ReadLine(…) – reads a single line of – reads a single line of characterscharacters
OutputOutput Write(…)Write(…) – prints the specified – prints the specified
argument on the consoleargument on the console
WriteLine(…WriteLine(…)) – prints specified data to the – prints specified data to the console and moves to the next lineconsole and moves to the next line
5
Console.Write(…)Console.Write(…)
Printing more than one variable Printing more than one variable using a formatting stringusing a formatting string
int a = 15;int a = 15;......Console.Write(a); // 15Console.Write(a); // 15
Printing an integer variablePrinting an integer variable
double a = 15.5;double a = 15.5;int b = 14;int b = 14;......Console.Write("{0} + {1} = {2}", a, b, a + b);Console.Write("{0} + {1} = {2}", a, b, a + b);// 15.5 + 14 = 29.5// 15.5 + 14 = 29.5
Next print operation will start from Next print operation will start from the same linethe same line
6
Console.WriteLine(…)Console.WriteLine(…)
Printing more than one variable Printing more than one variable using a formatting stringusing a formatting string
string str = "Hello C#!";string str = "Hello C#!";......Console.WriteLine(str);Console.WriteLine(str);
Printing a string variablePrinting a string variable
string name = "Marry";string name = "Marry";int year = 1987;int year = 1987;......Console.Write("{0} was born in {1}.", name, year);Console.Write("{0} was born in {1}.", name, year);// Marry was born in 1987.// Marry was born in 1987.
Next printing will start from the next Next printing will start from the next lineline
7
Printing to the Console – Printing to the Console – ExampleExample
static void Main()static void Main(){{ string name = "Peter";string name = "Peter"; int age = 18;int age = 18; string town = "Sofia";string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",Console.Write("{0} is {1} years old from {2}.", name, age, town);name, age, town); // Result: Peter is 18 years old from Sofia.// Result: Peter is 18 years old from Sofia. Console.Write("This is on the same line!");Console.Write("This is on the same line!"); Console.WriteLine("Next sentence will be" +Console.WriteLine("Next sentence will be" + " on a new line.");" on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.",Console.WriteLine("Bye, bye, {0} from {1}.", name, town);name, town);} }
8
Using Parameters – Using Parameters – ExampleExample
9
static void Main()static void Main(){{ int a=2, b=3;int a=2, b=3; Console.Write("{0} + {1} =", a, b);Console.Write("{0} + {1} =", a, b); Console.WriteLine(" {0}", a+b);Console.WriteLine(" {0}", a+b); // 2 + 3 = 5// 2 + 3 = 5
Console.WriteLine("{0} * {1} = {2}",Console.WriteLine("{0} * {1} = {2}", a, b, a*b);a, b, a*b); // 2 * 3 = 6// 2 * 3 = 6
float pi = 3.14159206;float pi = 3.14159206; Console.WriteLine("{0:F2}", pi); // 3,14Console.WriteLine("{0:F2}", pi); // 3,14 Console.WriteLine("Bye – Bye!");Console.WriteLine("Bye – Bye!");} }
Printing a Menu – Printing a Menu – ExampleExample
double colaPrice = 1.20;double colaPrice = 1.20;string cola = "Coca Cola";string cola = "Coca Cola";double fantaPrice = 1.20;double fantaPrice = 1.20;string fanta = "Fanta Dizzy";string fanta = "Fanta Dizzy";double zagorkaPrice = 1.50;double zagorkaPrice = 1.50;string zagorka = "Zagorka";string zagorka = "Zagorka";
Console.WriteLine("Menu:");Console.WriteLine("Menu:");Console.WriteLine("1. {0} – {1}",Console.WriteLine("1. {0} – {1}",
cola, colaPrice);cola, colaPrice);Console.WriteLine("2. {0} – {1}",Console.WriteLine("2. {0} – {1}",
fanta, fantaPrice);fanta, fantaPrice);Console.WriteLine("3. {0} – {1}",Console.WriteLine("3. {0} – {1}",
zagorka, zagorkaPrice);zagorka, zagorkaPrice);Console.WriteLine("Have a nice day!");Console.WriteLine("Have a nice day!");
10
Printing Printing to the to the
ConsoleConsoleLive DemoLive Demo
Reading from the Reading from the ConsoleConsoleReading Strings and Reading Strings and Numeral TypesNumeral Types
Reading from the Reading from the ConsoleConsole
We use the console to read We use the console to read information from the command lineinformation from the command line
We can read:We can read: CharactersCharacters StringsStrings Numeral types (after conversion)Numeral types (after conversion)
To read from the console we use To read from the console we use the methods the methods Console.Read()Console.Read() and and Console.ReadLine()Console.ReadLine()
13
Console.Read()Console.Read() Gets a single character from the Gets a single character from the
console (after [Enter] is pressed)console (after [Enter] is pressed) Returns a result of type Returns a result of type intint
Returns Returns -1-1 if there aren’t more if there aren’t more symbolssymbols
To get the actually read character we To get the actually read character we
need to cast it to need to cast it to charcharint i = Console.Read();int i = Console.Read();char ch = (char) i; // Cast the int to charchar ch = (char) i; // Cast the int to char
// Gets the code of the entered symbol// Gets the code of the entered symbolConsole.WriteLine("The code of '{0}' is {1}.", Console.WriteLine("The code of '{0}' is {1}.", ch, i);ch, i);
14
Reading Reading Characters fromCharacters from
the Consolethe ConsoleLive DemoLive Demo
Console.ReadKey()Console.ReadKey() Waits until a combination of keys is Waits until a combination of keys is
pressedpressed Reads a single character from console Reads a single character from console
or a combination of keysor a combination of keys Returns a result of type Returns a result of type ConsoleKeyInfoConsoleKeyInfo KeyCharKeyChar – holds the entered character – holds the entered character
ModifiersModifiers – holds the state of [Ctrl], – holds the state of [Ctrl], [Alt], …[Alt], …
ConsoleKeyInfo key = Console.ReadKey();ConsoleKeyInfo key = Console.ReadKey();Console.WriteLine();Console.WriteLine();Console.WriteLine("Character entered: " + Console.WriteLine("Character entered: " + key.KeyChar);key.KeyChar);Console.WriteLine("Special keys: " + Console.WriteLine("Special keys: " + key.Modifiers);key.Modifiers);
16
Reading Keys Reading Keys from the from the ConsoleConsole
Live DemoLive Demo
Console.ReadLine()Console.ReadLine()
Gets a line of charactersGets a line of characters Returns a Returns a stringstring value value Returns Returns nullnull if the end of the input if the end of the input
is reachedis reachedConsole.Write("Please enter your first name: ");Console.Write("Please enter your first name: ");string firstName = Console.ReadLine();string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");Console.Write("Please enter your last name: ");string lastName = Console.ReadLine();string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!",Console.WriteLine("Hello, {0} {1}!", firstName, lastName);firstName, lastName);
18
Reading Reading Strings from Strings from the Consolethe Console
Live DemoLive Demo
Reading Numeral TypesReading Numeral Types Numeral types can not be read directly Numeral types can not be read directly
from the consolefrom the console To read a numeral type do the following:To read a numeral type do the following:
1.1.RRead a string valueead a string value
2.2.Convert (parse) it to the required numeral Convert (parse) it to the required numeral typetype
int.Parse(string)int.Parse(string) – parses a – parses a stringstring to to intintstring str = Console.ReadLine()string str = Console.ReadLine()int number = int.Parse(str);int number = int.Parse(str);
Console.WriteLine("You entered: {0}", number);Console.WriteLine("You entered: {0}", number);
20
Converting Strings to Converting Strings to NumbersNumbers
Numeral types have a method Numeral types have a method Parse(…)Parse(…) for extracting the numeral value from a for extracting the numeral value from a stringstring int.Parse(string)int.Parse(string) – – stringstring intint longlong.Parse(string).Parse(string) – – stringstring longlong floatfloat.Parse(string).Parse(string) – – stringstring floatfloat Causes Causes FormatExceptionFormatException in case ofin case of errorerror
string s = "123";string s = "123";int i = int.Parse(s); // i = 123int i = int.Parse(s); // i = 123long l = long.Parse(s); // l = 123Llong l = long.Parse(s); // l = 123L
string invalid = "xxx1845";string invalid = "xxx1845";int value = int.Parse(invalid); // FormatExceptionint value = int.Parse(invalid); // FormatException
21
Reading Numbers from Reading Numbers from the the
Console – ExampleConsole – Example
22
static void Main()static void Main(){{ int a = int.Parse(Console.ReadLine());int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}",Console.WriteLine("{0} + {1} = {2}", a, b, a+b);a, b, a+b); Console.WriteLine("{0} * {1} = {2}",Console.WriteLine("{0} * {1} = {2}", a, b, a*b);a, b, a*b);
float f = float.Parse(Console.ReadLine());float f = float.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}",Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);a, b, f, a*b/f);}}
Converting Strings to Converting Strings to Numbers (2)Numbers (2)
Converting can also be done using the Converting can also be done using the methods of the methods of the ConvertConvert class class Convert.ToInt32(string)Convert.ToInt32(string) – – stringstring intint
Convert.ToSingle(string)Convert.ToSingle(string)– – stringstring floatfloat
Convert.ToInt64(string)Convert.ToInt64(string)– – stringstring longlong
Internally uses the parse methods of the Internally uses the parse methods of the numeral typesnumeral types
string s = "123";string s = "123";int i = Convert.ToInt32(s); // i = 123int i = Convert.ToInt32(s); // i = 123long l = Convert.ToInt64(s); // l = 123Llong l = Convert.ToInt64(s); // l = 123L
string invalid = "xxx1845";string invalid = "xxx1845";int value = Convert.ToInt32(invalid); // int value = Convert.ToInt32(invalid); // FormatExceptionFormatException
23
Reading Reading Numbers Numbers from the from the ConsoleConsoleLive DemoLive Demo
Error Handling when Error Handling when ParsingParsing
Sometimes we want to handle the errors Sometimes we want to handle the errors when parsing a numberwhen parsing a number Two options: use Two options: use trytry--catchcatch block or block or TryParse()TryParse()
Parsing with Parsing with TryParse()TryParse()::
string str = Console.ReadLine();string str = Console.ReadLine();int number;int number;if (int.TryParse(str, out number))if (int.TryParse(str, out number)){{ Console.WriteLine("Valid number: {0}", Console.WriteLine("Valid number: {0}", number);number);}}elseelse{{ Console.WriteLine("Invalid number: {0}", str);Console.WriteLine("Invalid number: {0}", str);}}
25
Parsing with Parsing with TryParseTryParse()()
Live DemoLive Demo
Reading and Reading and Printing to the Printing to the
ConsoleConsoleVarious ExamplesVarious Examples
Printing a Letter – Printing a Letter – ExampleExample
28
Console.Write("Enter person name: ");Console.Write("Enter person name: ");string person = Console.ReadLine();string person = Console.ReadLine();
Console.Write("Enter company name: ");Console.Write("Enter company name: ");string company = Console.ReadLine();string company = Console.ReadLine();
Console.WriteLine(" Dear {0},", person);Console.WriteLine(" Dear {0},", person);Console.WriteLine("We are pleased to tell you " + Console.WriteLine("We are pleased to tell you " + "that {1} has chosen you to take part " +"that {1} has chosen you to take part " + "in the \"Introduction To Programming\" " + "in the \"Introduction To Programming\" " + "course. {1} wishes you good luck!","course. {1} wishes you good luck!", person, company);person, company);
Console.WriteLine(" Yours,");Console.WriteLine(" Yours,");Console.WriteLine(" {0}", company);Console.WriteLine(" {0}", company);
Printing a LetterPrinting a LetterLive DemoLive Demo
Calculating Area – Calculating Area – ExampleExample
Console.WriteLine("This program calculates " +Console.WriteLine("This program calculates " + "the area of a rectangle or a triangle");"the area of a rectangle or a triangle");
Console.Write("Enter a and b (for rectangle) " +Console.Write("Enter a and b (for rectangle) " + " or a and h (for triangle): ");" or a and h (for triangle): ");int a = int.Parse(Console.ReadLine());int a = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());
Console.Write("Enter 1 for a rectangle or 2 " +Console.Write("Enter 1 for a rectangle or 2 " + "for a triangle: ");"for a triangle: ");
int choice = int.Parse(Console.ReadLine());int choice = int.Parse(Console.ReadLine());double area = (double) (a*b) / choice;double area = (double) (a*b) / choice;Console.WriteLine("The area of your figure " +Console.WriteLine("The area of your figure " + " is {0}", area);" is {0}", area);
30
Calculating AreaCalculating AreaLive DemoLive Demo
SummarySummary
We have discussed the basic input We have discussed the basic input and output methods of the classand output methods of the class ConsoleConsole Write(…)Write(…) and and WriteLine(WriteLine(……))
Used to write values to the consoleUsed to write values to the console
Read(…)Read(…) and and ReadLine(ReadLine(……)) Used to read values from the Used to read values from the
consoleconsole
Parsing numbers to stringsParsing numbers to strings int.Parse(…)int.Parse(…), , double.Parse(…)double.Parse(…), …, …
32
QuestionsQuestions??
Console Input / OutputConsole Input / Output
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that reads Write a program that reads 33 integer integer numbers from the console and prints numbers from the console and prints their sum.their sum.
2.2. Write a program that reads the radius Write a program that reads the radius rr of a circle and prints its perimeter and of a circle and prints its perimeter and area.area.
3.3. A company has name, address, phone A company has name, address, phone number, fax number, web site and number, fax number, web site and manager. The manager has first name, manager. The manager has first name, last name, age and a phone number. last name, age and a phone number. Write a program that reads the Write a program that reads the information about a company and its information about a company and its manager and prints them on the console.manager and prints them on the console. 34
Exercises (2)Exercises (2)
4.4. Write a program that reads two positive Write a program that reads two positive integer numbers and prints how many integer numbers and prints how many numbers numbers pp exist between them such exist between them such that the reminder of the division by that the reminder of the division by 55 is is 00 (inclusive). Example: (inclusive). Example: p(17,25)p(17,25) == 22..
5.5. Write a program that gets two numbers Write a program that gets two numbers from the console and prints the greater from the console and prints the greater of them. Don’t use of them. Don’t use ifif statements.statements.
6.6. Write a program that reads the Write a program that reads the coefficients coefficients aa, , bb and and cc of a quadratic of a quadratic equation equation aaxx22+b+bxx+c=0+c=0 and solves it (prints and solves it (prints its real roots).its real roots).
35
Exercises (3)Exercises (3)
7.7. Write a program that gets a number Write a program that gets a number nn and and after that gets more after that gets more nn numbers and numbers and calculates and prints their sum. calculates and prints their sum.
8.8. Write a program that reads an integer Write a program that reads an integer number number nn from the console and prints all from the console and prints all the numbers in the interval [the numbers in the interval [11....nn], each on a ], each on a single line.single line.
9.9. Write a program to print the first 100 Write a program to print the first 100 members of the sequence of Fibonaccimembers of the sequence of Fibonacci: 0, 1, : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …377, …
10.10. Write a program to calculate the sum (with Write a program to calculate the sum (with accuracy of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 accuracy of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ...+ ... 36
Recommended