Introduction to the Console

Overview

To allow you to display things on the monitor's screen, the .NET Framework provides a class named Console. The Console class is defined in the System namespace. The System namespace is part of the mscorlib.dll library. When you create a C# application, the mscorlib.dll library is directly available; which means you don't have to import it.

The Console class is static. This means means that you never have to declare a variable for it in order to use it.

Practical LearningPractical Learning: Introducing Data Reading

  1. Launch  Microsoft Visual Studio
  2. To start a new project, on the main menu, click File -> New -> Project
  3. In the middle list, click Empty Project (.NET Framework)
  4. Change the Name to GeorgetownDryCleaningServices3
  5. Click OK
  6. In the Solution Explorer, right-click GeorgetownDryCleaningServices3 -> Add -> New Item...
  7. In the left list of the dialog box, under Visual C#, click Code
  8. In the middle list, click Code File
  9. Change the Name to ClearningOrder
  10. Press Enter

Writing to the Console

To provide the ability to display one or more values to the screen, the Console class is equipped with a mehod named Write. To use the Write() method, inside of the parentheses, type the value you want to display. Here is an example for a string:

public class Exercise
{
    static void Main()
    {
        System.Console.Write("The Wonderful World of C# Programming");
    }
}

To be able to handle any value of the data types we have used so far, the Write() method is overloaded with various versions, a version that takes an argument for each data type:

public static void Write(int value);
public static void Write(string value);
public static void Write(double value);
public static void Write(object value);

Writing With a New Line

After displaying a value on the screen, the Write() method keeps the caret on the same line. To give you the ability to move the caret to the next line after displaying a value, the Console class is equipped with a method named WriteLine. Like Write(), the WriteLine() method has a version for each of the data types we have used so far: 

public static void WriteLine(int value);
public static void WriteLine(string value);
public static void WriteLine(double value);
public static void WriteLine(object value);

Besides these versions, the Write() and the WriteLine() methods have each a version that takes an unlimited number of arguments:

public static void WriteLine(. . .);
public static void WriteLine(. . .);

To get skeleton code for System.Console.WriteLine, right-click the line where you want to add it and click Insert Snippet... Double-click Visual C#. In the list, double-click cw:

cw

Reading a Value

We saw that the Console class allows using the Write() or the WriteLine() methods to display values on the screen. While the Console.Write() method is used to display something on the screen, the Console class provides a method named Read. It is used to get a value from the user. To use it, the name of a variable can be assigned to it. The syntax used is:

variable-name = Console.Read();

This simply means that, when the user types something and presses Enter, what the user had typed would be given (the word is assigned) to the variable specified on the left side of the assignment operator.

Read() doesn't always have to assign its value to a variable. For example, it can be used on its own line, which simply means that the user is expected to type something but the value typed by the user would not be used for any significant purpose. For example some versions of C# would display the DOS window briefly and disappear. You can use the Read() method to wait for the user to press any key in order to close the DOS window.

Reading With a New Line

Besides Read(), the Console class also provides a method named ReadLine. Like the WriteLine() method, after performing its assignment, the ReadLine() method sends the caret to the next line. Otherwise, it plays the same role as the Read() function.

Characteristics and Behaviors of a Console

The Title of a Console Screen

A console window is primarily a normal window with classic behaviors. It is equipped with a title bar that displays a title. By default, the title bar displays the path of the Command Prompt:

Title

The Console class allows you to change the title of the console. To do this, assign a string to Console.Title. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        Console.Title = "Department Store"; 

        return 0;
    }
}

Title

Clearing the Console

If the console screen is filled with text you don't need anymore, you can empty it. To allow you to clear the screen, the Console class is equipped with a method named Clear. It syntax is:

public static void Clear();

Data Reading

String Value Request

In most assignments of your programs, you may want the user to provide such a string. To request a string (or any of the variables we will see in this lesson), you can call the Console.Read() or the Console.ReadLine() function and assign it to the name of the variable whose value you want to retrieve. Here is an example:

using System;

public class Exercise
{
    public static void Main()
    {
        string firstName;

        Console.Write("Enter First Name: ");
        firstName = Console.ReadLine();
    }
}

Practical LearningPractical Learning: Reading String Values

  1. To request strings from the user, change the document as follows:
    using System;
    
    public class CleaningOrder
    {
        public static int Main()
        {
            string customerName, homePhone;
    
            Console.Title = "Georgetown Dry Cleaning Services";
            Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            // Request customer information from the user
            Console.Write("Enter Customer Name:  ");
            customerName = Console.ReadLine();
            Console.Write("Enter Customer Phone: ");
            homePhone = Console.ReadLine();
    
            Console.Clear();
            Console.Title = "Georgetown Dry Cleaning Services";
    
            // Display the receipt
            Console.WriteLine("========================================");
            Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            Console.WriteLine("========================================");
            Console.Write("Customer:   ");
            Console.WriteLine(customerName);
            Console.Write("Home Phone: ");
            Console.WriteLine(homePhone);
            Console.WriteLine("========================================\n");
    
            return 0;
        }
    }
  2. To execute the program, on the main menu, click Debug -> Start Without Debugging
  3. When asked to provide a customer name, type a name, such as James Watson:
  4. Press Enter
  5. When asked to provide a phone number, type something, such as (410) 493-2005
    -/- Georgetown Dry Cleaning Services -/-
    Enter Customer Name:  James Watson
    Enter Customer Phone: (410) 493-2005
  6. Press Enter:
    ========================================
    -/- Georgetown Dry Cleaning Services -/-
    ========================================
    Customer:   James Watson
    Home Phone: (410) 493-2005
    ========================================
  7. Press Enter to close the DOS window and return to your programming environment

Number Request

In C#, everything the user types is a string and the compiler would hardly analyze it without your explicit asking it to do so. Therefore, if you want to get a number from the user, first request a string. Here is an example:

using System;

public class Exercise
{
    public static void Main()
    {
        int number;
        string strNumber;

        strnumber = Console.ReadLine();
    }
}

After getting the string, you must convert it to a number. To perform this conversion, each data type of the .NET Framework provides a mechanism called Parse. To use Parse(), type the data type, followed by a period, followed by Parse, and followed by parentheses. In the parentheses of Parse, type the string that you requested from the user. Here is an example:

using System;

public class Exercise
{
    public static void Main()
    {
        int number;
        string strNumber;

        strnumber = Console.ReadLine();
        number = int.Parse(strNumber);
    }
}

An advanced but faster way to do this is to type Console.ReadLine() in the parentheses of Parse. This has the same effect. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        int number;

        number = int.Parse(Console.ReadLine());
        
        return 0;
    }
}

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
    using static System.Console;
    
    public class CleaningOrder
    {
        public static int Main()
        {
            // Price of items
            const double PriceOneShirt = 0.95;
            const double PriceAPairOfPants = 2.95;
            const double PriceOneDress = 4.55;
            const double TaxRate = 0.0575;  // 5.75%
    
            // Customer personal infoirmation
            string customerName, homePhone;
            // Unsigned numbers to represent cleaning items
            int numberOfShirts, numberOfPants, numberOfDresses;
            // Each of these sub totals will be used for cleaning items
            double subTotalShirts, subTotalPants, subTotalDresses;
            // Values used to process an order
            double totalOrder, taxAmount, salesTotal;
            double amountTended, moneyChange;
    
            Title = "Georgetown Dry Cleaning Services";
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            // Request customer information from the user
            Write("Enter Customer Name:  ");
            customerName = ReadLine();
            Write("Enter Customer Phone: ");
            homePhone = ReadLine();
    
            // Request the quantity of each category of items
            Write("Number of Shirts:  ");
            string strShirts = ReadLine();
            numberOfShirts = int.Parse(strShirts);
    
            Write("Number of Pants:   ");
            string strPants = ReadLine();
            numberOfPants = int.Parse(strPants);
    
            Write("Number of Dresses: ");
            string strDresses = ReadLine();
            numberOfDresses = int.Parse(strDresses);
    
            // Perform the necessary calculations
            subTotalShirts = numberOfShirts * PriceOneShirt;
            subTotalPants = numberOfPants * PriceAPairOfPants;
            subTotalDresses = numberOfDresses * PriceOneDress;
            // Calculate the "temporary" total of the order
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
            // Calculate the tax amount using a constant rate
            taxAmount = totalOrder * TaxRate;
            // Add the tax amount to the total order
            salesTotal = totalOrder + taxAmount;
    
            // Communicate the total to the user...
            Write("\nThe Total order is: ");
            WriteLine(salesTotal);
            // and request money for the order
            Write("Amount Tended? ");
            amountTended = double.Parse(ReadLine());
    
            // Calculate the difference owed to the customer
            // or that the customer still owes to the store
            moneyChange = amountTended - salesTotal;
    
            Clear();
            Title = "Georgetown Dry Cleaning Services";
    
            // Display the receipt
            WriteLine("====================================");
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            WriteLine("====================================");
            Write("Customer:   ");
            WriteLine(customerName);
            Write("Home Phone: ");
            WriteLine(homePhone);
            WriteLine("------------------------------------");
            WriteLine("Item Type  Qty Unit/Price Sub-Total");
            WriteLine("------------------------------------");
            Write("Shirts      ");
            Write(numberOfShirts);
            Write("     ");
            Write(PriceOneShirt);
            Write("     ");
            WriteLine(subTotalShirts);
            Write("Pants       ");
            Write(numberOfPants);
            Write("     ");
            Write(PriceAPairOfPants);
            Write("     ");
            WriteLine(subTotalPants);
            Write("Dresses     ");
            Write(numberOfDresses);
            Write("     ");
            Write(PriceOneDress);
            Write("     ");
            WriteLine(subTotalDresses);
            WriteLine("------------------------------------");
            Write("Total Order:     ");
            WriteLine(totalOrder);
            Write("Tax Rate:        ");
            Write(TaxRate * 100);
            WriteLine('%');
            Write("Tax Amount:      ");
            WriteLine(taxAmount);
            Write("Net Price:       ");
            WriteLine(salesTotal);
            WriteLine("------------------------------------");
            Write("Amount Tended:   ");
            WriteLine(amountTended);
            Write("Difference:      ");
            WriteLine(moneyChange);
            WriteLine("====================================");
    
            return 0;
        }
    }
  2. To execute the program and test it, on the main menu, click Debug -> Start Without Debugging. Here is an example:
    -/- Georgetown Dry Cleaning Services -/-
    Enter Customer Name:  Genevieve Alton
    Enter Customer Phone: (202) 974-8244
    Number of Shirts:  8
    Number of Pants:   2
    Number of Dresses: 3
    
    The Total order is: 28.711125
    Amount Tended? 30
  3. Press Enter
    ===============================
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:   Genevieve Alton
    Home Phone: (202) 974-8244
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      8     0.95     7.60
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Total Order:     27.15
    Tax Rate:        5.7500%
    Tax Amount:      1.561125
    Net Price:       28.711125
    ------------------------------------
    Amount Tended:   30
    Difference:      1.288875
    ====================================
  4. Press Enter to close the DOS window and return to your programming environment
  5. To deal with new dates and times, change the program as follows:
    using System;
    using static System.Console;
    
    public class OrderProcessing
    {
        public static int Main()
        {
            // Price of items
            const double PriceOneShirt = 0.95;
            const double PriceAPairOfPants = 2.95;
            const double PriceOneDress = 4.55;
            const double TaxRate = 0.0575;  // 5.75%
    
            // Basic information about an order
            string customerName, homePhone;
            DateTime orderDate;
            // Unsigned numbers to represent cleaning items
            int numberOfShirts, numberOfPants, numberOfDresses;
            // Each of these sub totals will be used for cleaning items
            double subTotalShirts, subTotalPants, subTotalDresses;
            // Values used to process an order
            double totalOrder, taxAmount, salesTotal;
            double amountTended, moneyChange;
    
            Title = "Georgetown Dry Cleaning Services";
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            // Request order information from the user
            Write("Enter Customer Name:  ");
            customerName = ReadLine();
            Write("Enter Customer Phone: ");
            homePhone = ReadLine();
            WriteLine("Enter the order date and " +
                    "time (mm/dd/yyyy hh:mm AM/PM)");
            orderDate = DateTime.Parse(ReadLine());
    
            // Request the quantity of each category of items
            Write("Number of Shirts:  ");
            string strShirts = ReadLine();
            numberOfShirts = int.Parse(strShirts);
    
            Write("Number of Pants:   ");
            string strPants = ReadLine();
            numberOfPants = int.Parse(strPants);
    
            Write("Number of Dresses: ");
            string strDresses = ReadLine();
            numberOfDresses = int.Parse(strDresses);
    
            // Perform the necessary calculations
            subTotalShirts = numberOfShirts * PriceOneShirt;
            subTotalPants = numberOfPants * PriceAPairOfPants;
            subTotalDresses = numberOfDresses * PriceOneDress;
            // Calculate the "temporary" total of the order
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
            // Calculate the tax amount using a constant rate
            taxAmount = totalOrder * TaxRate;
            // Add the tax amount to the total order
            salesTotal = totalOrder + taxAmount;
    
            // Communicate the total to the user...
            Write("The Total order is: ");
            WriteLine(salesTotal);
            // and request money for the order
            Write("Amount Tended? ");
            amountTended = double.Parse(ReadLine());
    
            // Calculate the difference owed to the customer
            // or that the customer still owes to the store
            moneyChange = amountTended - salesTotal;
    
            Clear();
            Title = "Georgetown Dry Cleaning Services";
    
            // Display the receipt
            WriteLine("====================================");
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            WriteLine("====================================");
            Write("Customer:    ");
            WriteLine(customerName);
            Write("Home Phone:  ");
            WriteLine(homePhone);
            Write("Date & Time: ");
            WriteLine(orderDate);
            WriteLine("------------------------------------");
            WriteLine("Item Type  Qty Unit/Price Sub-Total");
            WriteLine("------------------------------------");
            Write("Shirts      ");
            Write(numberOfShirts);
            Write("     ");
            Write(PriceOneShirt);
            Write("     ");
            WriteLine(subTotalShirts);
            Write("Pants       ");
            Write(numberOfPants);
            Write("     ");
            Write(PriceAPairOfPants);
            Write("     ");
            WriteLine(subTotalPants);
            Write("Dresses     ");
            Write(numberOfDresses);
            Write("     ");
            Write(PriceOneDress);
            Write("     ");
            WriteLine(subTotalDresses);
            WriteLine("------------------------------------");
            Write("Total Order:     ");
            WriteLine(totalOrder);
            Write("Tax Rate:        ");
            Write(TaxRate * 100);
            WriteLine('%');
            Write("Tax Amount:      ");
            WriteLine(taxAmount);
            Write("Net Price:       ");
            WriteLine(salesTotal);
            WriteLine("------------------------------------");
            Write("Amount Tended:   ");
            WriteLine(amountTended);
            Write("Difference:      ");
            WriteLine(moneyChange);
            WriteLine("====================================");
    
            return 0;
        }
    }
  6. Execute the program and test it. Here is an example:
    -/- Georgetown Dry Cleaning Services -/-
    Enter Customer Name:                Alexander Pappas
    Enter Customer Phone:               (301) 397-9764
    Enter the order date (mm/dd/yyyy):  06/22/2019
    Enter the order time (hh:mm AM/PM): 08:26 AM
    Number of Shirts:                   2
    Number of Pants:                    6
    Number of Dresses:                  4
    The Total order is:                 39.9735
    Amount Tended?                      40
  7. Press Enter:
    ====================================
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:    Alexander Pappas
    Home Phone:  (301) 397-9764
    Order Date:  06/22/2019
    Order Time:  08:26 AM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      2     0.95     1.9
    Pants       6     2.95     17.7
    Dresses     4     4.55     18.2
    ------------------------------------
    Total Order:     37.8
    Tax Rate:        5.75%
    Tax Amount:      2.1735
    Net Price:       39.9735
    ------------------------------------
    Amount Tended:   40
    Difference:      0.0265000000000057
    ====================================
    Press any key to continue . . .
  8. Press Enter to close the window and return to your programming environment

Formatting Data Display

Introduction

Instead of using two Write() or a combination of Write() and WriteLine() to display data, you can convert a value to a string and display it directly. To do this, you can provide two strings to the Write() or WriteLine() and separate them with a comma:

  1. The first part of the string provided to Write() or WriteLine() is the complete string that would display to the user. This first string itself can be made of different sections:
    1. One section is a string in any way you want it to display
    2. Another section is a number included between an opening curly bracket "{" and a closing curly bracket "}". This combination of "{" and "}" is a placeholder

      You can put the placeholder anywhere inside of the string. The first placeholder must have number 0. The second must have number 1, and so on. With this technique, you can create the string anyway you like and use the placeholders anywhere inside the string
  2. The second part of the string provided to Write() or WriteLine() is the value that you want to display. It can be one value if you used only one placeholder with 0 in the first string. If you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

using System;

public class Exercise
{
    public static void Main()
    {
        var fullName = "Anselme Bogos";
        var age = 15;
        var hSalary = 22.74;

        Console.WriteLine("Full Name: {0}", fullName);
        Console.WriteLine("Age: {0}", Age);
        Console.WriteLine("Distance: {0}", hSalary);
    }
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Distance: 22.74

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

Write("To Display {0} {1} {2} {n}", First, Second, Third, nth);

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

Practical LearningPractical Learning: Displaying Data With Placeholders

  1. To use curly brackets to display data, change the file as follows:
    using static System.Console;
    
    public class OrderProcessing
    {
        public static int Main()
        {
            // Price of items
            const double PriceOneShirt = 0.95;
            const double PriceAPairOfPants = 2.95;
            const double PriceOneDress = 4.55;
            const double TaxRate = 0.0575;  // 5.75%
    
            // Basic information about an order
            string customerName, homePhone;
            string orderDate, orderTime;
            // Unsigned numbers to represent cleaning items
            int numberOfShirts, numberOfPants, numberOfDresses;
            // Each of these sub totals will be used for cleaning items
            double subTotalShirts, subTotalPants, subTotalDresses;
            // Values used to process an order
            double totalOrder, taxAmount, salesTotal;
            double amountTended, moneyChange;
    
            Title = "Georgetown Dry Cleaning Services";
    
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            // Request order information from the user
            Write("Enter Customer Name:                ");
            customerName = ReadLine();
            Write("Enter Customer Phone:               ");
            homePhone = ReadLine();
            Write("Enter the order date (mm/dd/yyyy):  ");
            orderDate = ReadLine();
            Write("Enter the order time (hh:mm AM/PM): ");
            orderTime = ReadLine();
    
            // Request the quantity of each category of items
            Write("Number of Shirts:                   ");
            string strShirts = ReadLine();
            numberOfShirts = int.Parse(strShirts);
    
            Write("Number of Pants:                    ");
            string strPants = ReadLine();
            numberOfPants = int.Parse(strPants);
    
            Write("Number of Dresses:                  ");
            string strDresses = ReadLine();
            numberOfDresses = int.Parse(strDresses);
    
            // Perform the necessary calculations
            subTotalShirts = numberOfShirts * PriceOneShirt;
            subTotalPants = numberOfPants * PriceAPairOfPants;
            subTotalDresses = numberOfDresses * PriceOneDress;
            // Calculate the "temporary" total of the order
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
            // Calculate the tax amount using a constant rate
            taxAmount = totalOrder * TaxRate;
            // Add the tax amount to the total order
            salesTotal = totalOrder + taxAmount;
    
            // Communicate the total to the user...
            Write("The Total order is:               ");
            WriteLine(salesTotal);
            // and request money for the order
            Write("Amount Tended?                      ");
            amountTended = double.Parse(ReadLine());
    
            // Calculate the difference owed to the customer
            // or that the customer still owes to the store
            moneyChange = amountTended - salesTotal;
    
            Clear();
            Title = "Georgetown Dry Cleaning Services";
    
            // Display the receipt
            WriteLine("====================================");
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            WriteLine("====================================");
            WriteLine("Customer:    {0}", customerName);
            WriteLine("Home Phone:  {0}", homePhone);
            WriteLine("Order Date:  {0}", orderDate);
            WriteLine("Order Time:  {0}", orderTime);
            WriteLine("------------------------------------");
            WriteLine("Item Type  Qty Unit/Price Sub-Total");
            WriteLine("------------------------------------");
            WriteLine("Shirts      {0}     {1}     {2}",
                      numberOfShirts,
                      PriceOneShirt, subTotalShirts);
            WriteLine("Pants       {0}     {1}     {2}",
                      numberOfPants,
                      PriceAPairOfPants, subTotalPants);
            WriteLine("Dresses     {0}     {1}     {2}",
                      numberOfDresses,
                      PriceOneDress, subTotalDresses);
            WriteLine("------------------------------------");
            WriteLine("Total Order:     {0}", totalOrder);
            WriteLine("Tax Rate:        {0}%", TaxRate * 100);
            WriteLine("Tax Amount:      {0}", taxAmount);
            WriteLine("Net Price:       {0}", salesTotal);
            WriteLine("------------------------------------");
            WriteLine("Amount Tended:   {0}", amountTended);
            WriteLine("Difference:      {0}", moneyChange);
            WriteLine("====================================");
    
            return 0;
        }
    }
  2. To execute the program and test it, on the main menu, click Debug -> Start Without Debugging
  3. Enter some values. Here are examples:
    -/- Georgetown Dry Cleaning Services -/-
    Enter Customer Name:                Herman Kouvari
    Enter Customer Phone:               (202) 179-5040
    Enter the order date (mm/dd/yyyy):  06/30/2019
    Enter the order time (hh:mm AM/PM): 10:27
    Number of Shirts:                   6
    Number of Pants:                    2
    Number of Dresses:                  2
    The Total order is:                 21.89025
    Amount Tended?                      40
  4. Press Enter:
    ====================================
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:    Herman Kouvari
    Home Phone:  (202) 179-5040
    Order Date:  06/30/2019
    Order Time:  10:27
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      6     0.95     5.7
    Pants       2     2.95     5.9
    Dresses     2     4.55     9.1
    ------------------------------------
    Total Order:     20.7
    Tax Rate:        5.75%
    Tax Amount:      1.19025
    Net Price:       21.89025
    ------------------------------------
    Amount Tended:   40
    Difference:      18.10975
    ====================================
    Press any key to continue . . .
  5. Press Enter to close the DOS window and return to your programming environment

Number Formatting

To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to display it to the user. As it happens, you can display a natural number in a common value or else. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of the decimal separator and in some cases, you may want to display a salary with only 2 decimal places.

The System namespace provides a specific letter that you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letters from the following table. The letters and their meanings are:

Character Description
c C Currency values
d D Decimal numbers
e E Scientific numeric display such as 1.45e5
f F Fixed decimal numbers
d D General and most common type of numbers
n N Natural numbers
r R Roundtrip formatting
s S Hexadecimal formatting
p P Percentages

Line Formatting

So far, to position text of different lengths, we had to "corrupt" a string by including extra-empty spaces. Such a technique can be uncertain at times. Fortunately, you can highly format how a string or a line of text should display. The .NET Framework provides mechanisms to control the amount of space used to display a string of text and how to align that string on its line.

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placeholder and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width.

Practical LearningPractical Learning: Formatting Data Display

  1. To format data display, change the file as follows:
    using static System.Console;
    
    public class OrderProcessing
    {
        public static int Main()
        {
            // Price of items
            const double PriceOneShirt     = 0.95;
            const double PriceAPairOfPants = 2.95;
            const double PriceOneDress     = 4.55;
            const double TaxRate           = 5.75;  // 5.75%
    
            // Basic information about an order
            string customerName, homePhone;
            string orderDate, orderTime;
            // Unsigned numbers to represent cleaning items
            int numberOfShirts, numberOfPants, numberOfDresses;
            // Each of these sub totals will be used for cleaning items
            double subTotalShirts, subTotalPants, subTotalDresses;
            // Values used to process an order
            double totalOrder, taxAmount, salesTotal;
            double amountTended, moneyChange;
    
            Title = "Georgetown Dry Cleaning Services";
    
            WriteLine("===============================================");
            WriteLine("-/-    Georgetown Dry Cleaning Services    -/-");
            WriteLine("==============================================");
            // Request order information from the user
            Write("Enter Customer Name:                ");
            customerName = ReadLine();
            Write("Enter Customer Phone:               ");
            homePhone = ReadLine();
            Write("Enter the order date (mm/dd/yyyy):  ");
            orderDate = ReadLine();
            Write("Enter the order time (hh:mm AM/PM): ");
            orderTime = ReadLine();
    
            // Request the quantity of each category of items
            Write("Number of Shirts:                   ");
            string strShirts = ReadLine();
            numberOfShirts = int.Parse(strShirts);
    
            Write("Number of Pants:                    ");
            string strPants = ReadLine();
            numberOfPants = int.Parse(strPants);
    
            Write("Number of Dresses:                  ");
            string strDresses = ReadLine();
            numberOfDresses = int.Parse(strDresses);
    
            // Perform the necessary calculations
            subTotalShirts = numberOfShirts * PriceOneShirt;
            subTotalPants = numberOfPants * PriceAPairOfPants;
            subTotalDresses = numberOfDresses * PriceOneDress;
            // Calculate the "temporary" total of the order
            totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
            // Calculate the tax amount using a constant rate
            taxAmount = totalOrder * TaxRate / 100.00;
            // Add the tax amount to the total order
            salesTotal = totalOrder + taxAmount;
    
            WriteLine("-----------------------------------------");
            // Communicate the total to the user...
            WriteLine("The Total order is:                 {0:C}", salesTotal);
            // and request money for the order
            Write("Amount Tended?                      ");
            amountTended = double.Parse(ReadLine());
    
            // Calculate the difference owed to the customer
            // or that the customer still owes to the store
            moneyChange = amountTended - salesTotal;
    
            Clear();
            Title = "Georgetown Dry Cleaning Services";
    
            // Display the receipt
            WriteLine("=========================================");
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            WriteLine("=========================================");
            WriteLine("Customer:   {0}", customerName);
            WriteLine("Home Phone: {0}", homePhone);
            WriteLine("Order Date: {0}", orderDate);
            WriteLine("Order Time: {0}", orderTime);
            WriteLine("-----------------------------------------");
            WriteLine("Item Type  Qty Unit/Price Sub-Total");
            WriteLine("-----------------------------------------");
            WriteLine("Shirts{0,7}     {1:C}     {2:C}",
                      numberOfShirts, PriceOneShirt, subTotalShirts);
            WriteLine("Pants{0,8}     {1:C}     {2:C}",
                      numberOfPants, PriceAPairOfPants, subTotalPants);
            WriteLine("Dresses{0,6}     {1:C}     {2:C}",
                      numberOfDresses, PriceOneDress, subTotalDresses);
            WriteLine("-----------------------------------------");
            WriteLine("Total Order:     {0:C}", totalOrder);
            WriteLine("Tax Rate:        {0:P}", TaxRate / 100);
            WriteLine("Tax Amount:      {0:C}", taxAmount);
            WriteLine("Net Price:       {0:C}", salesTotal);
            WriteLine("-----------------------------------------");
            WriteLine("Amount Tended:   {0:C}", amountTended);
            WriteLine("Difference:      {0:C}", moneyChange);
            WriteLine("=========================================");
    
            return 0;
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging. Here is an example:
    ===============================================
    -/-    Georgetown Dry Cleaning Services    -/-
    ==============================================
    Enter Customer Name:                Gretchen McCormack
    Enter Customer Phone:               (410) 739-2884
    Enter the order date (mm/dd/yyyy):  10/27/2019
    Enter the order time (hh:mm AM/PM): 18:42
    Number of Shirts:                   12
    Number of Pants:                    8
    Number of Dresses:                  6
    -----------------------------------------
    The Total order is:                 $65.88
    Amount Tended?                      70
  3. Press Enter:
    =========================================
    -/- Georgetown Dry Cleaning Services -/-
    =========================================
    Customer:   Gretchen McCormack
    Home Phone: (410) 739-2884
    Order Date: 10/27/2019
    Order Time: 18:42
    -----------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    -----------------------------------------
    Shirts     12     $0.95     $11.40
    Pants       8     $2.95     $23.60
    Dresses     6     $4.55     $27.30
    -----------------------------------------
    Total Order:     $62.30
    Tax Rate:        5.75 %
    Tax Amount:      $3.58
    Net Price:       $65.88
    -----------------------------------------
    Amount Tended:   $70.00
    Difference:      $4.12
    =========================================
    Press any key to continue . . .
  4. Press Enter to close the DOS window and return to your programming environment
  5. Close your programming environment

Previous Copyright © 2001-2019, FunctionX Next