0% found this document useful (0 votes)
8 views

4 Console Input Output 202ed6c75dafcbd047818c9ac26e7fd5

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

4 Console Input Output 202ed6c75dafcbd047818c9ac26e7fd5

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

3/14/2018

Console Input / Output


Reading and Writing to the Console

Printing to the Console


Printing Strings, Numeral Types and Expressions

Printing to the Console The Console Class


 Console is used to display information in a text  Provides methods for console input and output
window  Input
 Can display different values:  Read(…) – reads a single character
 Strings  ReadKey(…) – reads a combination of keys
 Numeral types  ReadLine(…) – reads a single line of characters
 All primitive data types  Output
 To print to the console use the class Console  Write(…) – prints the specified
(System.Console) argument on the console
 WriteLine(…) – prints specified data to the
console and moves to the next line
3 4

Console.Write(…) Console.WriteLine(…)
 Printing an integer variable  Printing a string variable
int a = 15; string str = "Hello C#!";
... ...
Console.Write(a); // 15 Console.WriteLine(str);

 Printing more than one variable using a  Printing more than one variable using a
formatting string formatting string
double a = 15.5; string name = "Marry";
int b = 14; int year = 1987;
... ...
Console.Write("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} was born in {1}.", name, year);
// 15.5 + 14 = 29.5 // Marry was born in 1987.

 Next print operation will start from the same line  Next printing will start from the new line
5 6

1
3/14/2018

Printing to the Console – Example Formatting Strings


static void Main()  {index[,alignment][:formatString]}
{
string name = "Peter";  index
int age = 18;
string town = "Sofia";  The zero-based index of the argument whose
string representation is to be included at this
Console.Write("{0} is {1} years old from {2}.",
name, age, town); position in the string
// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");  alignment
Console.WriteLine("Next sentence will be" +
" on a new line.");  A signed integer that indicates the total length
of the field into which the argument is inserted
Console.WriteLine("Bye, bye, {0} from {1}.",
name, town);  a positive integer – right-aligned
}
 a negative integer – left-aligned
7

Formatting Strings Formatting Strings – Example


 {index[,alignment][:formatString]}
static void Main()
 formatString {
int a=2, b=3;
 Specifies the format of the corresponding Console.Write("{0} + {1} =", a, b);
Console.WriteLine(" {0}", a+b);
argument's result string, e.g. "X", "C", "0.00" // 2 + 3 = 5

 Example: Console.WriteLine("{0} * {1} = {2}",


a, b, a*b);
// 2 * 3 = 6
static void Main()
{ float pi = 3.14159206;
double pi = 1.234; Console.WriteLine("{0:F2}", pi); // 3,14
Console.WriteLine("{0:0.000000}", pi);
// 1.234000 Console.WriteLine("Bye – Bye!");
} }

10

Printing a Menu – Example


double colaPrice = 1.20;
string cola = "Coca Cola";
double
string
fantaPrice = 1.20;
fanta = "Fanta Dizzy"; Reading from the Console
double zagorkaPrice = 1.50;
string zagorka = "Zagorka"; Reading Strings and Numeral Types
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!");

11

2
3/14/2018

Reading from the Console Console.Read()


 We use the console to read information from  Gets a single character from the console (after
[Enter] is pressed)
the command line
 Returns a result of type int
 We can read:
 Returns -1 if there aren’t more symbols
 Characters
 To get the actually read character we
 Strings need to cast it to char
 Numeral types (after conversion)
int i = Console.Read();
char ch = (char) i; // Cast the int to char
 To read from the console we use the methods
// Gets the code of the entered symbol
Console.Read() and Console.ReadLine() Console.WriteLine("The code of '{0}' is {1}.", ch, i);

13 14

Console.ReadKey() Console.ReadLine()
 Waits until a combination of keys is pressed
 Gets a line of characters
 Reads a single character from console or a
 Returns a string value
combination of keys
 Returns null if the end of the input is reached
 Returns a result of type ConsoleKeyInfo
 KeyChar – holds the entered character Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
 Modifiers – holds the state of [Ctrl], [Alt], …
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine(); Console.WriteLine("Hello, {0} {1}!",
Console.WriteLine("Character entered: " + key.KeyChar); firstName, lastName);
Console.WriteLine("Special keys: " + key.Modifiers);

15 16

Reading Numeral Types Converting Strings to Numbers


 Numeral types can not be read directly from the  Numeral types have a method Parse(…) for
console extracting the numeral value from a string
 To read a numeral type do the following:  int.Parse(string) – string  int
1. Read a string value  long.Parse(string) – string  long
2. Convert (parse) it to the required numeral type  float.Parse(string) – string  float
 int.Parse(string)  Causes FormatException in case of error
 Parses (converts) a string to int
string s = "123";
int i = int.Parse(s); // i = 123
string str = Console.ReadLine()
long l = long.Parse(s); // l = 123L
int number = int.Parse(str);
string invalid = "xxx1845";
Console.WriteLine("You entered: {0}", number); int value = int.Parse(invalid); // FormatException
17 18

3
3/14/2018

Reading Numbers from Converting Strings


the Console – Example to Numbers (2)
 Converting can also be done using the methods of
static void Main() the Convert class
{
int a = int.Parse(Console.ReadLine());  Convert.ToInt32(string) – string  int
int b = int.Parse(Console.ReadLine());
 Convert.ToSingle(string)– string  float
Console.WriteLine("{0} + {1} = {2}",
a, b, a+b);  Convert.ToInt64(string)– string  long
Console.WriteLine("{0} * {1} = {2}",
a, b, a*b);  It uses the parse methods of the numeral types
float f = float.Parse(Console.ReadLine()); string s = "123";
Console.WriteLine("{0} * {1} / {2} = {3}", int i = Convert.ToInt32(s); // i = 123
a, b, f, a*b/f); long l = Convert.ToInt64(s); // l = 123L
} string invalid = "xxx1845";
int value = Convert.ToInt32(invalid); // FormatException
19 20

Error Handling when Parsing


 Sometimes we want to handle the errors when
parsing a number
 Two options: use try-catch block or TryParse()
 Parsing with TryParse():
string str = Console.ReadLine();
int number;
if (int.TryParse(str, out number))
{
Console.WriteLine("Valid number: {0}", number); Regional Settings
}
else Printing and Reading Special Characters
{
Console.WriteLine("Invalid number: {0}", str); Regional Settings and the Number Formatting
}

21

How to Print Special Decimal Separator


Characters on the Console?
 The currency format and number formats are
 Printing special characters on the console needs
two steps: different in different countries
 Change the console properties  E.g. the decimal separator could be "." or ","
to enable Unicode-friendly font  To ensure the decimal separator is "." use the
 Enable Unicode for the Console following code:
by adjusting its output encoding using System.Threading;
using System.Globalization;
 Prefer UTF8 (Unicode) …
Thread.CurrentThread.CurrentCulture =
using System.Text; CultureInfo.InvariantCulture;

Console.WriteLine(3.54); // 3.54
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Това е кирилица: ☺"); decimal value = decimal.Parse("1.33");
23 24

4
3/14/2018

Printing a Letter – Example Calculating Area – Example

Console.Write("Enter person name: "); Console.WriteLine("This program calculates " +


string person = Console.ReadLine(); "the area of a rectangle or a triangle");

Console.Write("Enter company name: "); Console.Write("Enter a and b (for rectangle) " +


string company = Console.ReadLine(); " or a and h (for triangle): ");
int a = int.Parse(Console.ReadLine());
Console.WriteLine(" Dear {0},", person); int b = int.Parse(Console.ReadLine());
Console.WriteLine("We are pleased to tell you " +
"that {1} has chosen you to take part " + Console.Write("Enter 1 for a rectangle or 2 " +
"in the \"Introduction To Programming\" " + "for a triangle: ");
"course. {1} wishes you good luck!",
person, company); int choice = int.Parse(Console.ReadLine());
double area = (double) (a*b) / choice;
Console.WriteLine(" Yours,"); Console.WriteLine("The area of your figure " +
Console.WriteLine(" {0}", company); " is {0}", area);

25 26

Exercises Exercises (2)


1. Write a program that reads 3 integer numbers from 4. Write a program that reads two positive integer
the console and prints their sum. numbers and prints how many numbers p exist
2. Write a program that reads the radius r of a circle between them such that the reminder of the division
and prints its perimeter and area. by 5 is 0 (inclusive). Example: p(17,25) = 2.

3. A company has name, address, phone number, fax 5. Write a program that gets two numbers from the
number, web site and manager. The manager has console and prints the greater of them. Don’t use if
first name, last name, age and a phone number. statements.
Write a program that reads the information about a 6. Write a program that reads the coefficients a, b and c
company and its manager and prints them on the of a quadratic equation ax2+bx+c=0 and solves it
console. (prints its real roots).

27 28

Exercises (3) Exercises (4)


7. Write a program that gets a number n and after that 11. * Implement the "Falling Rocks" game in the text
gets more n numbers and calculates and prints their console. A small dwarf stays at the bottom of the
sum. screen and can move left and right (by the arrows
keys). A number of rocks of different sizes and forms
8. Write a program that reads an integer number n
constantly fall down and you need to avoid a crash.
from the console and prints all the numbers in the
interval [1..n], each on a single line. ^ @ Rocks are the symbols ^,
* * @, *, &, +, %, $, #, !, ., ;,
9. Write a program to print the first 100 members of & + % $
- distributed with
+ .
the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, +++ # ! t appropriate density. The
34, 55, 89, 144, 233, 377, … + ; *
dwarf is (O). Ensure a
. * ++
10. Write a program to calculate the sum (with accuracy . * -- constant game speed by
; . (O) @
of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ... Thread.Sleep(150).
Implement collision detection and scoring system.
29 30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy