SlideShare uma empresa Scribd logo
1 de 41
Console Input / Output
Reading and Writing to the Console
Svetlin Nakov
Technical Trainer
www.nakov.com
Software University
http://softuni.bg
2
1. Printing to the Console
 Printing Strings and Numbers
2. Reading from the Console
 Reading Characters
 Reading Strings
 Parsing Strings to Numeral Types
 Reading Numeral Types
3. Various Examples
Table of Contents
Printing to the Console
Printing Strings, Numeral Types
and Expressions
4
 The console (terminal window) is used to read / display text-
based information in a virtual terminal window
 Learn more from Wikipedia: terminal emulator, virtual console
 Can display different values:
 Strings
 Numeral types
 All primitive data types
 To print to the console use the
Console class (System.Console)
Printing to the Console
5
 Provides methods for console input and output
 Input
 Read(…) – reads a single character
 ReadKey(…) – reads a combination of keys
 ReadLine(…) – reads a single line of characters
 Output
 Write(…) – prints the specified argument on the console
 WriteLine(…) – prints specified data to the console and moves
to the next line
The Console Class
6
 Printing an integer variable:
 Printing more than one variable using a formatting string:
Console.Write(…)
int a = 15;
Console.Write(a); // 15
double a = 15.5;
int b = 14;
...
Console.Write("{0} + {1} = {2}", a, b, a + b);
// 15.5 + 14 = 29.5
 The next print operation will start from the same line
7
Console.WriteLine(…)
 Printing more than one variable using a formatting string:
string str = "Hello C#!";
Console.WriteLine(str);
 Printing a string variable + new line (rn):
string name = "Marry";
int year = 1987;
...
Console.WriteLine("{0} was born in {1}.", name, year);
// Marry was born in 1987.
 Next printing will start from the new line
8
Printing to the Console – Example
static void Main()
{
string name = "Peter";
int age = 18;
string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",
name, age, town);
// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");
Console.WriteLine("Next sentence will be on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.", name, town);
}
 index
 The zero-based index of the argument whose string
representation is to be included at this position in the string
 alignment
 A signed integer that indicates the total length of the field into
which the argument is inserted
 a positive integer – right-aligned
 a negative integer – left-aligned
Formatting Strings
{index[,alignment][:formatString]}
 formatString
 Specifies the format of the corresponding argument's result string,
e.g. "X", "C", "0.00", e.g.
Formatting Strings (2)
static void Main()
{
double pi = 1.234;
Console.WriteLine("{0:0.000000}", pi);
// 1.234000
}
{index[,alignment][:formatString]}
11
Formatting Strings – Examples
static void Main()
{
int a=2, b=3;
Console.Write("{0} + {1} =", a, b);
Console.WriteLine(" {0}", a+b);
// 2 + 3 = 5
Console.WriteLine("{0} * {1} = {2}", a, b, a*b);
// 2 * 3 = 6
float pi = 3.14159206;
Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14
Console.WriteLine("Bye – Bye!");
}
12
Printing a Menu – Example
double colaPrice = 1.20;
string cola = "Coca Cola";
double fantaPrice = 1.20;
string fanta = "Fanta Dizzy";
double zagorkaPrice = 1.50;
string zagorka = "Zagorka";
Console.WriteLine("Menu:");
Console.WriteLine("1. {0} – {1}", cola, colaPrice);
Console.WriteLine("2. {0} – {1}", fanta, fantaPrice);
Console.WriteLine("3. {0} – {1}", zagorka, zagorkaPrice);
Console.WriteLine("Have a nice day!");
Printing to
the Console
Live Demo
Reading from the Console
Reading Strings and Numeral Types
15
 We use the console to read information from the command line
 Usually the data is entered from the keyboard
 We can read:
 Characters
 Strings
 Numeral types (after conversion)
 To read from the console we use the methods
Console.Read() and Console.ReadLine()
Reading from the Console
16
 Gets a single character from the console (after [Enter] is
pressed)
 Returns a result of type int
 Returns -1 if there aren’t more symbols
 To get the actually read character we need to cast it to char
Console.Read()
int i = Console.Read();
char ch = (char) i; // Cast the int to char
// Gets the code of the entered symbol
Console.WriteLine("The code of '{0}' is {1}.", ch, i);
Reading Characters
from the Console
Live Demo
18
 Waits until a combination of keys is pressed
 Reads a single character from console or a combination of keys
 Returns a result of type ConsoleKeyInfo
 KeyChar – holds the entered character
 Modifiers – holds the state of [Ctrl], [Alt], …
Console.ReadKey()
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Character entered: " + key.KeyChar);
Console.WriteLine("Special keys: " + key.Modifiers);
Reading Keys from the Console
Live Demo
20
 Gets a line of characters
 Returns a string value
 Returns null if the end of the input is reached
Console.ReadLine()
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
Reading Strings from the Console
Live Demo
22
 Numeral types can not be read directly from the console
 To read a numeral type do the following:
1. Read a string value
2. Convert (parse) it to the required numeral type
 int.Parse(string)
 Parses (converts) a string to int
Reading Numeral Types
string str = Console.ReadLine()
int number = int.Parse(str);
Console.WriteLine("You entered: {0}", number);
23
 Numeral types have a method Parse(…)
for extracting the numeral value from a string
 int.Parse(string) – string  int
 long.Parse(string) – string  long
 float.Parse(string) – string  float
 Causes FormatException in case of error
Converting Strings to Numbers
string s = "123";
int i = int.Parse(s); // i = 123
long l = long.Parse(s); // l = 123L
string invalid = "xxx1845";
int value = int.Parse(invalid); // FormatException
24
Reading Numbers from the Console – Example
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}", a, b, a+b);
Console.WriteLine("{0} * {1} = {2}", a, b, a*b);
float f = float.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);
}
25
 Converting can also be done through the Convert class
 Convert.ToInt32(string[, base]) – string  int
 Convert.ToSingle(string)– string  float
 Convert.ToInt64(string)– string  long
 It uses the parse methods of the numeral types
Converting Strings to Numbers (2)
string s = "123";
int i = Convert.ToInt32(s); // i = 123
long l = Convert.ToInt64(s); // l = 123L
string invalid = "xxx1845";
int value = Convert.ToInt32(invalid); // FormatException
Reading Numbers from the Console
Live Demo
27
 Sometimes we want to handle the errors when parsing a number
 Two options: use try-catch block or TryParse()
 Parsing with TryParse():
Error Handling when Parsing
string str = Console.ReadLine();
int number;
if (int.TryParse(str, out number))
{
Console.WriteLine("Valid number: {0}", number);
}
else
{
Console.WriteLine("Invalid number: {0}", str);
}
Parsing with TryParse()
Live Demo
Regional Settings
Printing and Reading Special Characters
Regional Settings and the Number Formatting
30
 Printing special characters on the console needs two steps:
 Change the console properties
to enable Unicode-friendly font
 Enable Unicode for the Console
by adjusting its output encoding
 Prefer UTF8 (Unicode)
How to Print Special Characters on the Console?
using System.Text;
…
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Това е кирилица: ☺");
31
 The currency format and number formats are different in
different countries
 E.g. the decimal separator could be "." or ","
 To ensure the decimal separator is "." use the following code:
Decimal Separator
using System.Threading;
using System.Globalization;
…
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(3.54); // 3.54
decimal value = decimal.Parse("1.33");
Regional Settings
Live Demo
Reading and Printing to the Console
Various Examples
34
Printing a Letter – Example
Console.Write("Enter person name: ");
string person = Console.ReadLine();
Console.Write("Enter company name: ");
string company = Console.ReadLine();
Console.WriteLine(" Dear {0},", person);
Console.WriteLine("We are pleased to tell you that " +
"{1} has accepted you to take part in the "C# Basics"" +
" course. {1} wishes you a good luck!", person, company);
Console.WriteLine(" Yours,");
Console.WriteLine(" {0}", company);
Printing a Letter
Live Demo
36
Calculating Area – Example
Console.WriteLine("This program calculates " +
"the area of a rectangle or a triangle");
Console.Write("Enter a and b (for rectangle) " +
" or a and h (for triangle): ");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.Write("Enter 1 for a rectangle or 2 for a triangle: ");
int choice = int.Parse(Console.ReadLine());
double area = (double) (a*b) / choice;
Console.WriteLine("The area of your figure is {0}", area);
Calculating Area
Live Demo
38
 Basic input and output methods of the class Console
 Write(…) and WriteLine(…)
 Write values to the console
 Read(…) and ReadLine(…)
 Read values from the console
 Parsing numbers to strings
 int.Parse(…)
 double.Parse(…)
 …
Summary
?
http://softuni.bg/courses/csharp-basics/
Console Input / Output
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
40
 Attribution: this work may contain portions from
 "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license
 "C# Part I" course by Telerik Academy under CC-BY-NC-SA license
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

Mais conteúdo relacionado

Mais procurados

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 

Mais procurados (20)

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Interface
InterfaceInterface
Interface
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
Generics C#
Generics C#Generics C#
Generics C#
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
 
String handling in_java
String handling in_javaString handling in_java
String handling in_java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
Java input
Java inputJava input
Java input
 

Semelhante a 04. Console Input Output

16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
(02) c sharp_tutorial
(02) c sharp_tutorial(02) c sharp_tutorial
(02) c sharp_tutorial
Satish Verma
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
MAHESHV559910
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
Doncho Minkov
 

Semelhante a 04. Console Input Output (20)

04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 
Write and write line methods
Write and write line methodsWrite and write line methods
Write and write line methods
 
C# basics
 C# basics C# basics
C# basics
 
C#.net
C#.netC#.net
C#.net
 
Wlkthru vb netconsole-inputoutput
Wlkthru vb netconsole-inputoutputWlkthru vb netconsole-inputoutput
Wlkthru vb netconsole-inputoutput
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
python-ch2.pptx
python-ch2.pptxpython-ch2.pptx
python-ch2.pptx
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
(02) c sharp_tutorial
(02) c sharp_tutorial(02) c sharp_tutorial
(02) c sharp_tutorial
 
7512635.ppt
7512635.ppt7512635.ppt
7512635.ppt
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
SPL 3 | Introduction to C programming
SPL 3 | Introduction to C programmingSPL 3 | Introduction to C programming
SPL 3 | Introduction to C programming
 
The Art of Clean Code
The Art of Clean CodeThe Art of Clean Code
The Art of Clean Code
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
5_IntermediateCodeGeneration.ppt
5_IntermediateCodeGeneration.ppt5_IntermediateCodeGeneration.ppt
5_IntermediateCodeGeneration.ppt
 

Mais de Intro C# Book

Mais de Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 

Último

VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
nirzagarg
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
imonikaupta
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 

Último (20)

Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
 

04. Console Input Output

  • 1. Console Input / Output Reading and Writing to the Console Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg
  • 2. 2 1. Printing to the Console  Printing Strings and Numbers 2. Reading from the Console  Reading Characters  Reading Strings  Parsing Strings to Numeral Types  Reading Numeral Types 3. Various Examples Table of Contents
  • 3. Printing to the Console Printing Strings, Numeral Types and Expressions
  • 4. 4  The console (terminal window) is used to read / display text- based information in a virtual terminal window  Learn more from Wikipedia: terminal emulator, virtual console  Can display different values:  Strings  Numeral types  All primitive data types  To print to the console use the Console class (System.Console) Printing to the Console
  • 5. 5  Provides methods for console input and output  Input  Read(…) – reads a single character  ReadKey(…) – reads a combination of keys  ReadLine(…) – reads a single line of characters  Output  Write(…) – prints the specified argument on the console  WriteLine(…) – prints specified data to the console and moves to the next line The Console Class
  • 6. 6  Printing an integer variable:  Printing more than one variable using a formatting string: Console.Write(…) int a = 15; Console.Write(a); // 15 double a = 15.5; int b = 14; ... Console.Write("{0} + {1} = {2}", a, b, a + b); // 15.5 + 14 = 29.5  The next print operation will start from the same line
  • 7. 7 Console.WriteLine(…)  Printing more than one variable using a formatting string: string str = "Hello C#!"; Console.WriteLine(str);  Printing a string variable + new line (rn): string name = "Marry"; int year = 1987; ... Console.WriteLine("{0} was born in {1}.", name, year); // Marry was born in 1987.  Next printing will start from the new line
  • 8. 8 Printing to the Console – Example static void Main() { string name = "Peter"; int age = 18; string town = "Sofia"; Console.Write("{0} is {1} years old from {2}.", name, age, town); // Result: Peter is 18 years old from Sofia. Console.Write("This is on the same line!"); Console.WriteLine("Next sentence will be on a new line."); Console.WriteLine("Bye, bye, {0} from {1}.", name, town); }
  • 9.  index  The zero-based index of the argument whose string representation is to be included at this position in the string  alignment  A signed integer that indicates the total length of the field into which the argument is inserted  a positive integer – right-aligned  a negative integer – left-aligned Formatting Strings {index[,alignment][:formatString]}
  • 10.  formatString  Specifies the format of the corresponding argument's result string, e.g. "X", "C", "0.00", e.g. Formatting Strings (2) static void Main() { double pi = 1.234; Console.WriteLine("{0:0.000000}", pi); // 1.234000 } {index[,alignment][:formatString]}
  • 11. 11 Formatting Strings – Examples static void Main() { int a=2, b=3; Console.Write("{0} + {1} =", a, b); Console.WriteLine(" {0}", a+b); // 2 + 3 = 5 Console.WriteLine("{0} * {1} = {2}", a, b, a*b); // 2 * 3 = 6 float pi = 3.14159206; Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14 Console.WriteLine("Bye – Bye!"); }
  • 12. 12 Printing a Menu – Example double colaPrice = 1.20; string cola = "Coca Cola"; double fantaPrice = 1.20; string fanta = "Fanta Dizzy"; double zagorkaPrice = 1.50; string zagorka = "Zagorka"; Console.WriteLine("Menu:"); Console.WriteLine("1. {0} – {1}", cola, colaPrice); Console.WriteLine("2. {0} – {1}", fanta, fantaPrice); Console.WriteLine("3. {0} – {1}", zagorka, zagorkaPrice); Console.WriteLine("Have a nice day!");
  • 14. Reading from the Console Reading Strings and Numeral Types
  • 15. 15  We use the console to read information from the command line  Usually the data is entered from the keyboard  We can read:  Characters  Strings  Numeral types (after conversion)  To read from the console we use the methods Console.Read() and Console.ReadLine() Reading from the Console
  • 16. 16  Gets a single character from the console (after [Enter] is pressed)  Returns a result of type int  Returns -1 if there aren’t more symbols  To get the actually read character we need to cast it to char Console.Read() int i = Console.Read(); char ch = (char) i; // Cast the int to char // Gets the code of the entered symbol Console.WriteLine("The code of '{0}' is {1}.", ch, i);
  • 17. Reading Characters from the Console Live Demo
  • 18. 18  Waits until a combination of keys is pressed  Reads a single character from console or a combination of keys  Returns a result of type ConsoleKeyInfo  KeyChar – holds the entered character  Modifiers – holds the state of [Ctrl], [Alt], … Console.ReadKey() ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); Console.WriteLine("Character entered: " + key.KeyChar); Console.WriteLine("Special keys: " + key.Modifiers);
  • 19. Reading Keys from the Console Live Demo
  • 20. 20  Gets a line of characters  Returns a string value  Returns null if the end of the input is reached Console.ReadLine() Console.Write("Please enter your first name: "); string firstName = Console.ReadLine(); Console.Write("Please enter your last name: "); string lastName = Console.ReadLine(); Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
  • 21. Reading Strings from the Console Live Demo
  • 22. 22  Numeral types can not be read directly from the console  To read a numeral type do the following: 1. Read a string value 2. Convert (parse) it to the required numeral type  int.Parse(string)  Parses (converts) a string to int Reading Numeral Types string str = Console.ReadLine() int number = int.Parse(str); Console.WriteLine("You entered: {0}", number);
  • 23. 23  Numeral types have a method Parse(…) for extracting the numeral value from a string  int.Parse(string) – string  int  long.Parse(string) – string  long  float.Parse(string) – string  float  Causes FormatException in case of error Converting Strings to Numbers string s = "123"; int i = int.Parse(s); // i = 123 long l = long.Parse(s); // l = 123L string invalid = "xxx1845"; int value = int.Parse(invalid); // FormatException
  • 24. 24 Reading Numbers from the Console – Example static void Main() { int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); Console.WriteLine("{0} + {1} = {2}", a, b, a+b); Console.WriteLine("{0} * {1} = {2}", a, b, a*b); float f = float.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f); }
  • 25. 25  Converting can also be done through the Convert class  Convert.ToInt32(string[, base]) – string  int  Convert.ToSingle(string)– string  float  Convert.ToInt64(string)– string  long  It uses the parse methods of the numeral types Converting Strings to Numbers (2) string s = "123"; int i = Convert.ToInt32(s); // i = 123 long l = Convert.ToInt64(s); // l = 123L string invalid = "xxx1845"; int value = Convert.ToInt32(invalid); // FormatException
  • 26. Reading Numbers from the Console Live Demo
  • 27. 27  Sometimes we want to handle the errors when parsing a number  Two options: use try-catch block or TryParse()  Parsing with TryParse(): Error Handling when Parsing string str = Console.ReadLine(); int number; if (int.TryParse(str, out number)) { Console.WriteLine("Valid number: {0}", number); } else { Console.WriteLine("Invalid number: {0}", str); }
  • 29. Regional Settings Printing and Reading Special Characters Regional Settings and the Number Formatting
  • 30. 30  Printing special characters on the console needs two steps:  Change the console properties to enable Unicode-friendly font  Enable Unicode for the Console by adjusting its output encoding  Prefer UTF8 (Unicode) How to Print Special Characters on the Console? using System.Text; … Console.OutputEncoding = Encoding.UTF8; Console.WriteLine("Това е кирилица: ☺");
  • 31. 31  The currency format and number formats are different in different countries  E.g. the decimal separator could be "." or ","  To ensure the decimal separator is "." use the following code: Decimal Separator using System.Threading; using System.Globalization; … Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Console.WriteLine(3.54); // 3.54 decimal value = decimal.Parse("1.33");
  • 33. Reading and Printing to the Console Various Examples
  • 34. 34 Printing a Letter – Example Console.Write("Enter person name: "); string person = Console.ReadLine(); Console.Write("Enter company name: "); string company = Console.ReadLine(); Console.WriteLine(" Dear {0},", person); Console.WriteLine("We are pleased to tell you that " + "{1} has accepted you to take part in the "C# Basics"" + " course. {1} wishes you a good luck!", person, company); Console.WriteLine(" Yours,"); Console.WriteLine(" {0}", company);
  • 36. 36 Calculating Area – Example Console.WriteLine("This program calculates " + "the area of a rectangle or a triangle"); Console.Write("Enter a and b (for rectangle) " + " or a and h (for triangle): "); int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); Console.Write("Enter 1 for a rectangle or 2 for a triangle: "); int choice = int.Parse(Console.ReadLine()); double area = (double) (a*b) / choice; Console.WriteLine("The area of your figure is {0}", area);
  • 38. 38  Basic input and output methods of the class Console  Write(…) and WriteLine(…)  Write values to the console  Read(…) and ReadLine(…)  Read values from the console  Parsing numbers to strings  int.Parse(…)  double.Parse(…)  … Summary
  • 40. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license 40  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license  "C# Part I" course by Telerik Academy under CC-BY-NC-SA license
  • 41. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg

Notas do Editor

  1. 07/16/96
  2. 07/16/96
  3. 07/16/96
  4. 07/16/96
  5. 07/16/96
  6. 07/16/96
  7. 07/16/96
  8. 07/16/96
  9. 07/16/96
  10. 07/16/96
  11. 07/16/96