Reading and Writing to the Console Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Advertisements

Computer Programming w/ Eng. Applications
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Computer and Programming
Programming by Example Version 1.0. Objectives Take a small computing problem, and walk through the process of developing a solution. Investigate the.
C# Programming: From Problem Analysis to Program Design1 Methods and Behaviors C# Programming: From Problem Analysis to Program Design 3rd Edition 3.
Basic Input/Output and Variables Ethan Cerami New York
Integer, Floating-Point, Text Data, Variables, Literals Svetlin Nakov Telerik Corporation
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
Data Types, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods Svetlin Nakov Telerik Corporation
 Pearson Education, Inc. All rights reserved Formatted Output.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
Subroutines in Computer Programming Svetlin Nakov Telerik Corporation
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
3. Declaring Value-Type Variables
INPUT/OUTPUT STATEMENT ADDITION SLIDES. Console.ReadLine() – Use to get the input (String) from user Convert string to other data type – int.Parse() 
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
C# Language Overview (Part I)
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
1.3 Console Input And Output academy.zariba.com 1.
Chapter 2: Using Data.
Type Conversions Implicit Conversion Explicit Conversion.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Perform Calculations and Control Flow Telerik Software Academy Learning & Development Team.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
Introduction to Programming
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Introduction to Visual Basic Programming. Introduction Simple Program: Printing a Line of Text Another Simple Program: Adding Integers Memory Concepts.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Input & Output Statement
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C# Programming: Basic Concept Part 2 Computer and Programming (204111)
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
INPUT/OUTPUT STATEMENT ADDITION SLIDES. Console.ReadLine() – Use to get the input (String) from user Convert string to other data type – int.Parse() 
1 INPUT/OUTPUT Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Lecture 2 Review of 1301 and C# Richard Gesick. Common data types int, long, double, float, char, bool, string.
1 Statements © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License.
A Sample Program #include using namespace std; int main(void) { cout
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
Chapter 1.2 Introduction to C++ Programming
C# Basic Syntax, Visual Studio, Console Input / Output
C# Basic Syntax, Visual Studio, Console Input / Output
Using the Console.
Chapter 1.2 Introduction to C++ Programming
COMP 170 – Introduction to Object Oriented Programming
OUTPUT STATEMENTS GC 201.
Introduction to C++ Programming
Chapter 3 – Introduction to C# Programming
Lecture 1 Review of 1301/1321 CSE /26/2018.
C# Programming: From Problem Analysis to Program Design
Presentation transcript:

Reading and Writing to the Console Svetlin Nakov Telerik Corporation

 Printing to the Console  Printing Strings and Numbers  Reading from the Console  Reading Characters  Reading Strings  Parsing Strings to Numeral Types  Reading Numeral Types  Various Examples 2

Printing Strings, Numeral Types and Expressions

 Console is used to display information in a text window  Can display different values:  Strings  Numeral types  All primitive data types  To print to the console use the class Console ( System.Console ) 4

 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 5

 Printing more than one variable using a formatting string 6 int a = 15;... Console.Write(a); // 15  Printing an integer variable double a = 15.5; int b = 14;... Console.Write("{0} + {1} = {2}", a, b, a + b); // = 29.5  Next print operation will start from the same line

7  Printing more than one variable using a formatting string string str = "Hello C#!";...Console.WriteLine(str);  Printing a string variable string name = "Marry"; int year = 1987;... Console.WriteLine("{0} was born in {1}.", name, year); // Marry was born in  Next printing will start from the new line

8 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);}

 { index[, alignment][ : formatString] }  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

 { index[, alignment][ : formatString] }  formatString  Specifies the format of the corresponding argument's result string, e.g. " X ", " C ", " 0.00 "  Example: static void Main() { double pi = 1.234; double pi = 1.234; Console.WriteLine("{0: }", pi); Console.WriteLine("{0: }", pi); // // }

11 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}", Console.WriteLine("{0} * {1} = {2}", a, b, a*b); a, b, a*b); // 2 * 3 = 6 // 2 * 3 = 6 float pi = ; float pi = ; Console.WriteLine("{0:F2}", pi); // 3,14 Console.WriteLine("{0:F2}", pi); // 3,14 Console.WriteLine("Bye – Bye!"); Console.WriteLine("Bye – Bye!");}

12 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!");

Live Demo

Reading Strings and Numeral Types

 We use the console to read information from the command line  We can read:  Characters  Strings  Numeral types (after conversion)  To read from the console we use the methods Console.Read() and Console.ReadLine() 15

 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 16 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);

Live Demo

 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], … 18 ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); Console.WriteLine("Character entered: " + key.KeyChar); Console.WriteLine("Special keys: " + key.Modifiers);

Live Demo

 Gets a line of characters  Returns a string value  Returns null if the end of the input is reached 20 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); firstName, lastName);

Live Demo

 Numeral types can not be read directly from the console  To read a numeral type do the following: 1.R ead a string value 2.Convert (parse) it to the required numeral type  int.Parse(string)  Parses (converts) a string to int 22 string str = Console.ReadLine() int number = int.Parse(str); Console.WriteLine("You entered: {0}", number);

 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 23 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 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 can also be done using the methods of the Convert class  Convert.ToInt32(string) – string  int  Convert.ToSingle(string) – string  float  Convert.ToInt64(string) – string  long  It uses the parse methods of the numeral types 25 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

Live Demo

 Sometimes we want to handle the errors when parsing a number  Two options: use try - catch block or TryParse()  Parsing with TryParse() : 27 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);}

Live Demo

Printing and Reading Special Characters Regional Settings and the Number Formatting

 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) 30 using System.Text; … Console.OutputEncoding = Encoding.UTF8; Console.WriteLine("Това е кирилица: ☺");

 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: 31 using System.Threading; using System.Globalization; … Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.InvariantCulture; Console.WriteLine(3.54); // 3.54 decimal value = decimal.Parse("1.33");

Live Demo

Various Examples

34 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 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(" {0}", company);

Live Demo

36 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: "); "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); " is {0}", area);

Live Demo

 We have discussed the basic input and output methods of the class Console  Write(…) and WriteLine(…)  Used to write values to the console  Read(…) and ReadLine(…)  Used to read values from the console  Parsing numbers to strings  int.Parse(…), double.Parse(…), … 38

Questions?Questions?

1. Write a program that reads 3 integer numbers from the console and prints their sum. 2. Write a program that reads the radius r of a circle and prints its perimeter and area. 3. A company has name, address, phone number, fax number, web site and manager. The manager has first name, last name, age and a phone number. Write a program that reads the information about a company and its manager and prints them on the console. 40

4. Write a program that reads two positive integer numbers and prints how many numbers p exist between them such that the reminder of the division by 5 is 0 (inclusive). Example: p(17,25) = Write a program that gets two numbers from the console and prints the greater of them. Don’t use if statements. 6. Write a program that reads the coefficients a, b and c of a quadratic equation ax 2 +bx+c=0 and solves it (prints its real roots). 41

7. Write a program that gets a number n and after that gets more n numbers and calculates and prints their sum. 8. Write a program that reads an integer number n from the console and prints all the numbers in the interval [ 1.. n ], each on a single line. 9. Write a program to print the first 100 members of the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, … 10. Write a program to calculate the sum (with accuracy of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/

11. * Implement the "Falling Rocks" game in the text console. A small dwarf stays at the bottom of the screen and can move left and right (by the arrows keys). A number of rocks of different sizes and forms constantly fall down and you need to avoid a crash. 43 * * * * & + % $ +. & + % $ # ! +++ # ! + ; * + ; *. * ++. * --. * -- ;. t Rocks are the symbols *, &, +, %, $, #, !,., ;, - distributed with appropriate density. The dwarf is (O). Ensure a constant game speed by Thread.Sleep(150). Implement collision detection and scoring system.