Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Primitive Data Types and Variables Integer, Floating-Point, Text Data, Variables, Literals Angel Georgiev Part-time Trainer angeru.softuni-friends.org.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Programming Basics Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
1.3 Console Input And Output academy.zariba.com 1.
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Primitive Data Types and Variables Integer, Floating-Point, Text Data, Variables, Literals SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
C# Advanced Topics Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Objects and Classes Using Objects and Classes Defining Simple Classes SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
C# Basic Syntax, Visual Studio, Console Input / Output
C# Basic Syntax, Visual Studio, Console Input / Output
Repeating Code Multiple Times
Processing Variable-Length Sequences of Elements
Numeral Types and Type Conversion
Data Definition and Data Types
Presentation transcript:

Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University

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 consoleterminal emulatorvirtual 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); // = 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 ( \r\n ):new line string name = "Marry"; int year = 1987;... Console.WriteLine("{0} was born in {1}.", name, year); // Marry was born in // Interpolated Strings – from C#6 (VS 2015) Console.WriteLine("{name} was born in {year}.");  Next printing will start from the new line

8 Printing to the Console – Example 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 on a new line."); Console.WriteLine("Next sentence will be on a new line."); Console.WriteLine("Bye, bye, {0} from {1}.", name, town); 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; double pi = 1.234; Console.WriteLine("{0: }", pi); Console.WriteLine("{0: }", pi); // // } {index[,alignment][:formatString]}

11 Formatting Strings – Examples 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); // = 5 // = 5 Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); // 2 * 3 = 6 // 2 * 3 = 6 float pi = f; float pi = f; Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14 Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14 Console.WriteLine("Bye – Bye!"); 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 a = int.Parse(Console.ReadLine()); int b = 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); Console.WriteLine("{0} * {1} = {2}", a, b, a*b); Console.WriteLine("{0} * {1} = {2}", a, b, a*b); float f = float.Parse(Console.ReadLine()); float f = float.Parse(Console.ReadLine()); Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f); 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

Reading values from the Console Exercise

28  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); Console.WriteLine("Valid number: {0}", number);}else{ Console.WriteLine("Invalid number: {0}", str); Console.WriteLine("Invalid number: {0}", str);}

Parsing with TryParse() Live Demo

Regional Settings Printing and Reading Special Characters Regional Settings and the Number Formatting

31  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("Това е кирилица: ☺");

32  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

35 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 \"Programming Basics\"" + "{1} has accepted you to take part in the \"Programming Basics\"" + " course. {1} wishes you a good luck!", person, company); " course. {1} wishes you a good luck!", person, company); Console.WriteLine(" Yours,"); Console.WriteLine(" {0}", company);

Printing a Letter Live Demo

37 Calculating Area – Example 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) " + " or a and h (for triangle): "); " 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

39  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

? ? ? ? ? ? ? ? ? Console Input / Output

Homework Review Live Demo

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 42  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg