Data Reading and Writing to the Console
Data Reading and Writing to the Console
Introduction to the Console
Overview
To allow you to display simple values on the monitor's screen, the .NET Framework provides a static class named Console.
Practical Learning: Introducing the Console
Starting Console Code
The Console class is defined in the System namespace. Therefore, to use it in your application, in your code, you can type System followed by a period. If you are using the code Editor in Microsoft Visual Studio to create your application, its Intellisense would display the available classes of that 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. Since the Console class is static, you never have to declare a variable of it in order to use it. Therefore, to access the Console class in your code, after typing System and a period, type Console. To access a member of this class, type a period after its name.
Writing to the Console
To provide the ability to display one or more values to the screen, the Console class is equipped with a method named Write. To use the Write() method, inside its parentheses, type the value you want to display. Here is an example:
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. There is a version for each data type. The syntaxes are:
public static void Write(int value); public static void Write(uint value); public static void Write(string value); public static void Write(long value); public static void Write(ulong value); public static void Write(float value); public static void Write(double value); public static void Write(decimal 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(uint value); public static void WriteLine(string value); public static void WriteLine(long value); public static void WriteLine(ulong value); public static void WriteLine(float value); public static void WriteLine(double value); public static void WriteLine(decimal 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. Their syntaxes are:
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, position the mouse on Snippet, and click Insert Snippet... Double-click Visual C#. In the list, double-click cw:
Practical Learning: Introducing Data Writing
System.Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
-/- Georgetown Dry Cleaning Services -/- Press any key to continue . . .
Accessing the Members of the Console Class
Remember that, to access any class, you can qualify it from its namespace. Here is an example of calling a method of the Console class that is defined in the System namespace:
System.Console.WriteLine("The Wonderful World of C# Programming");
Using a Namespace
As you may know by now, to use a namespace, in your code, usually in the top section, type using followed by the name of the namespace. After doing that, you can access a class of the namespace in your code.
Practical Learning: Using a Namespace
using System; Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine(" Cursomer Order Processing"); Console.WriteLine("========================================");
-/- Georgetown Dry Cleaning Services -/- Cursomer Order Processing Press any key to continue . . .
Not Using the System
When you create a Console App in Microsoft Visual studio, the System namespace is automatically made available. As a result, as you don't have to "load" its library, you don't need the "using System;" line. If you omit that line, you can use the "Console.Write()" and the "Console.WriteLine()" expressions in your document.
Practical Learning: Omitting the System Namespace
Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine(" Cursomer Order Processing"); Console.WriteLine("========================================");
Statically Using a Namespace
Remember that, to access a static method, you can include using static followed by the name of the class in the top section of the document. Then, where needed, call the static method directly.
using static System.Console; WriteLine("The Wonderful World of C# Programming");
Reading a Value from the Console
Introduction
While the Console.Write() method is used to display something on the screen, the Console class provides a method named Read that 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.
The Read() method 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 a program display the DOS window briefly and disappear. You can use the Read() function to wait for the user to press any key in order to close the DOS window.
Reading a Key
As you may know already, each letter of the alphabet is represented on the keyboard by a key. Other symbols, readable (such as #, @, or $) or not (such as Shift, Ctrl, Space, or Enter) are also represented. To get the letter or the action that those keys represent, the Console class is equipped with a method named ReadKey that is overloaded with two versions. One of the versions uses the following syntax:
public static ConsoleKeyInfo ReadKey();
This method takes no argument but produces a value of a class named ConsoleKeyInfo. To get the value returned by this method, you can declare a ConsoleKeyInfo variable and assign it to the calling of this method.
If the user presses a key for a letter or a readable symbol (such as #, !, /, or %), to recognize the key that was pressed, the ConsoleKeyInfo class is equipped with a member named KeyChar. Here is an example of getting the letter:
ConsoleKeyInfo cki = new ConsoleKeyInfo(); Console.Write("Press a key: "); cki = Console.ReadKey(); Console.WriteLine(); Console.Write("You pressed: "); Console.WriteLine(cki.KeyChar); Console.ReadKey();
If the key that the user pressed is not a readable symbol such as the Space Bar, a Ctrl key, or Enter, to recognize it, the ConsoleKeyInfo class is equipped with a member named Key. Here is an example of using it:
ConsoleKeyInfo cki = new ConsoleKeyInfo();
Console.Write("Press a key: ");
cki = Console.ReadKey();
Console.WriteLine();
Console.Write("You pressed: ");
Console.WriteLine(cki.Key);
Console.ReadKey();
When it finishes reading its key, the Console.ReadKey() method stops and lets you decide what to do. If you want it to display the result, the Console class provides another version of the ReadKey() method. Its syntax is:
public static ConsoleKeyInfo ReadKey(bool intercept);
The Boolean argument specifies whether you want the method to display the value.
Reading With a New Line
Besides Read(), the Console class also provides the ReadLine() method. 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. Here is an example:
To allow you to change the title of its window, the Console class is equipped with a property named Console.Title. Here is an example of specifying the title of a console window:
Console.Title = "Department Store";
Practical Learning: Naming a Console Window
Console.Title = "Georgetown Dry Cleaning Services";
Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
Console.WriteLine(" Cursomer Order Processing");
Console.WriteLine("========================================");
Console.Title = "Georgetown Dry Cleaning Services"; Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine(" Cursomer Order Processing"); string customerName = "", homePhone = ""; // 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("========================================");
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();
Practical Learning: Clearing the Console
Console.Title = "Georgetown Dry Cleaning Services";
Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
Console.WriteLine(" Cursomer Order Processing");
string customerName = "", homePhone = "";
Console.Clear();
// 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("========================================");
Data Reading
String Value Request
In most cases the user provides a value in your application, you will not know that value. For example, you may want the user to provide a string. To request a string, you can call the Console.Read() or the Console.ReadLine() method and assign it to the name of the variable whose value you want to retrieve. Here is an example:
string firstName;
Console.Write("Enter First Name: ");
firstName = Console.ReadLine()!;
Practical Learning: Reading String Values
Console.Title = "Georgetown Dry Cleaning Services";
Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
Console.WriteLine(" Cursomer Order Processing");
string customerName = "", homePhone = "";
// Request customer information from the user
Console.Write("Enter Customer Name: ");
customerName = Console.ReadLine()!;
Console.Write("Enter Customer Phone: ");
homePhone = Console.ReadLine()!;
Console.Clear();
// 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("========================================");
-/- Georgetown Dry Cleaning Services -/- Cursomer Order Processing ======================================== Enter Customer Name: James Watson Enter Customer Phone: (410) 493-2005
======================================== -/- Georgetown Dry Cleaning Services -/- ======================================== Customer: James Watson Home Phone: (410) 493-2005 ======================================== Press any key to continue . . .
Number Request
Practically everything the user types in your program 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 static System.Console;
int number;
string strNumber;
strnumber = ReadLine();
After getting the string, you must convert it to a number. To perform this conversion, as we saw in previous lessons, each data type is represented in the .NET Framework by a structure that is equipped with a method named Parse. To convert a number, pass its variable to the Parse() method. Here is an example:
int number;
string strNumber;
strnumber = Console.ReadLine()!;
number = int.Parse(strNumber);
As an alternative, call the Console.Read() or the Console.ReadLine() method directly in the parentheses of the Parse() method. Here is an example:
int number;
number = int.Parse(Console.ReadLine());
Practical Learning: Reading Numeric Values
Console.Title = "Georgetown Dry Cleaning Services"; Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine(" Cursomer Order Processing"); Console.WriteLine("========================================"); // Price of items const double PriceOneShirt = 1.35; const double PriceAPairOfPants = 2.95; const double PriceOneDress = 4.55; const double TaxRate = 0.0575; // 5.75% // Request customer information from the user // Customer personal information Console.Write("Enter Customer Name: "); string customerName = Console.ReadLine()!; Console.Write("Enter Customer Phone: "); string homePhone = Console.ReadLine()!; // Request the quantity of each category of items Console.Write("Number of Shirts: "); string strShirts = Console.ReadLine()!; uint numberOfShirts = uint.Parse(strShirts); Console.Write("Number of Pants: "); string strPants = Console.ReadLine()!; uint numberOfPants = uint.Parse(strPants); Console.Write("Number of Dresses: "); string strDresses = Console.ReadLine()!; uint numberOfDresses = uint.Parse(strDresses); // Perform the necessary calculations double subTotalShirts = numberOfShirts * PriceOneShirt; double subTotalPants = numberOfPants * PriceAPairOfPants; double subTotalDresses = numberOfDresses * PriceOneDress; // Calculate the "temporary"total of the order double totalOrder = subTotalShirts + subTotalPants + subTotalDresses; // Calculate the tax amount using a constant rate double taxAmount = totalOrder * TaxRate; // Add the tax amount to the total order double salesTotal = totalOrder + taxAmount; // Communicate the total to the user... Console.Write("\nThe Total order is: "); Console.WriteLine(salesTotal); // and request money for the order Console.Write("Amount Tended? "); double amountTended = double.Parse(Console.ReadLine()!); // Calculate the difference owed to the customer // or that the customer still owes to the store double moneyChange = amountTended - salesTotal; Console.Clear(); // Display the receipt Console.WriteLine("========================================"); Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine("----------------------------------------"); Console.WriteLine(" Customer Cleaning Order"); Console.WriteLine("========================================"); Console.Write("Customer: "); Console.WriteLine(customerName); Console.Write("Home Phone: "); Console.WriteLine(homePhone); Console.WriteLine("----------------------------------------"); Console.WriteLine("Item Type Qty Unit/Price Sub-Total"); Console.WriteLine("----------------------------------------"); Console.Write("Shirts "); Console.Write(numberOfShirts); Console.Write(" "); Console.Write(PriceOneShirt); Console.Write(" "); Console.WriteLine(subTotalShirts); Console.Write("Pants "); Console.Write(numberOfPants); Console.Write(" "); Console.Write(PriceAPairOfPants); Console.Write(" "); Console.WriteLine(subTotalPants); Console.Write("Dresses "); Console.Write(numberOfDresses); Console.Write(" "); Console.Write(PriceOneDress); Console.Write(" "); Console.WriteLine(subTotalDresses); Console.WriteLine("----------------------------------------"); Console.Write("Total Order: "); Console.WriteLine(totalOrder); Console.Write("Tax Rate: "); Console.Write(TaxRate * 100); Console.WriteLine('%'); Console.Write("Tax Amount: "); Console.WriteLine(taxAmount); Console.Write("Net Price: "); Console.WriteLine(salesTotal); Console.WriteLine("----------------------------------------"); Console.Write("Amount Tended: "); Console.WriteLine(amountTended); Console.Write("Difference: "); Console.WriteLine(moneyChange); Console.WriteLine("========================================");
-/- Georgetown Dry Cleaning Services -/- Cursomer Order Processing ======================================== Enter Customer Name: James Watson Enter Customer Phone: (401) 493-2005 Number of Shirts: 8 Number of Pants: 3 Number of Dresses: 5 The Total order is: 44.838 Amount Tended? 50
======================================== -/- Georgetown Dry Cleaning Services -/- ---------------------------------------- Customer Cleaning Order ======================================== Customer: James Watson Home Phone: (401) 493-2005 ---------------------------------------- Item Type Qty Unit/Price Sub-Total ---------------------------------------- Shirts 8 1.35 10.8 Pants 3 2.95 8.85 Dresses 5 4.55 22.75 ---------------------------------------- Total Order: 42.4 Tax Rate: 5.75% Tax Amount: 2.438 Net Price: 44.838 ---------------------------------------- Amount Tended: 50 Difference: 5.16199999999999 ======================================== Press any key to continue . . .
Formatting Data Display
Introduction
Instead of using two Write() methods or a combination of theWrite() and the WriteLine() methods to display data, you can convert a value to a string and display it directly. To do this, you can provide two sections to the Write() or the WriteLine() methods and separate them with a comma:
Here are examples:
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 Learning: Displaying Data With Placeholders
Console.Title = "Georgetown Dry Cleaning Services";
Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
Console.WriteLine(" Cursomer Order Processing");
Console.WriteLine("========================================");
// Price of items
const double PriceOneShirt = 1.35;
const double PriceAPairOfPants = 2.95;
const double PriceOneDress = 4.55;
const double TaxRate = 0.0575; // 5.75%
// Request customer information from the user
// Customer personal infoirmation
Console.Write("Enter Customer Name: ");
string customerName = Console.ReadLine()!;
Console.Write("Enter Customer Phone: ");
string homePhone = Console.ReadLine()!;
// Request the quantity of each category of items
Console.Write("Number of Shirts: ");
string strShirts = Console.ReadLine()!;
uint numberOfShirts = uint.Parse(strShirts);
Console.Write("Number of Pants: ");
string strPants = Console.ReadLine()!;
uint numberOfPants = uint.Parse(strPants);
Console.Write("Number of Dresses: ");
string strDresses = Console.ReadLine()!;
uint numberOfDresses = uint.Parse(strDresses);
// Perform the necessary calculations
double subTotalShirts = numberOfShirts * PriceOneShirt;
double subTotalPants = numberOfPants * PriceAPairOfPants;
double subTotalDresses = numberOfDresses * PriceOneDress;
// Calculate the "temporary"total of the order
double totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
// Calculate the tax amount using a constant rate
double taxAmount = totalOrder * TaxRate;
// Add the tax amount to the total order
double salesTotal = totalOrder + taxAmount;
// Communicate the total to the user...
Console.Write("\nThe Total order is: ");
Console.WriteLine(salesTotal);
// and request money for the order
Console.Write("Amount Tended? ");
double amountTended = double.Parse(Console.ReadLine()!);
// Calculate the difference owed to the customer
// or that the customer still owes to the store
double moneyChange = amountTended - salesTotal;
Console.Clear();
// Display the receipt
Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
Console.WriteLine("====================================");
Console.WriteLine("Customer: {0}", customerName);
Console.WriteLine("Home Phone: {0}", homePhone);
Console.WriteLine("------------------------------------");
Console.WriteLine("Item Type Qty Unit/Price Sub-Total");
Console.WriteLine("------------------------------------");
Console.WriteLine("Shirts {0} {1} {2}",
numberOfShirts, PriceOneShirt, subTotalShirts);
Console.WriteLine("Pants {0} {1} {2}",
numberOfPants, PriceAPairOfPants, subTotalPants);
Console.WriteLine("Dresses {0} {1} {2}",
numberOfDresses, PriceOneDress, subTotalDresses);
Console.WriteLine("------------------------------------");
Console.WriteLine("Total Order: {0}", totalOrder);
Console.WriteLine("Tax Rate: {0}%", TaxRate * 100);
Console.WriteLine("Tax Amount: {0}", taxAmount);
Console.WriteLine("Net Price: {0}", salesTotal);
Console.WriteLine("------------------------------------");
Console.WriteLine("Amount Tended: {0}", amountTended);
Console.WriteLine("Difference: {0}", moneyChange);
Console.WriteLine("========================================");
-/- Georgetown Dry Cleaning Services -/- Cursomer Order Processing ======================================== Enter Customer Name: Jennifer Longhorn Enter Customer Phone: (142) 570-9274 Number of Shirts: 5 Number of Pants: 2 Number of Dresses: 7 The Total order is: 47.05875 Amount Tended? 48
-/- Georgetown Dry Cleaning Services -/- ==================================== Customer: Jennifer Longhorn Home Phone: (142) 570-9274 ------------------------------------ Item Type Qty Unit/Price Sub-Total ------------------------------------ Shirts 5 1.35 6.75 Pants 2 2.95 5.9 Dresses 7 4.55 31.85 ------------------------------------ Total Order: 44.5 Tax Rate: 5.75% Tax Amount: 2.55875 Net Price: 47.05875 ------------------------------------ Amount Tended: 48 Difference: 0.941249999999997 ======================================== Press any key to continue . . .
We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, the .NET Framework structure of each data type is equipped with a method named ToString. Normally, in C#, as we have done so far, this conversion is automatically or transparently done by the compiler. In some cases, you will need to perform the conversion yourself.
To convert a value of a primitive data type to a string, type the name of the variable, followed by a period, followed by ToString(). Here is an example:
string fullName = "Anselme Bogos"; int age = 15; double hSalary = 22.74; Console.WriteLine("Full Name: {0}", fullName); Console.WriteLine("Age: {0}", age.ToString()); Console.WriteLine("Distance: {0}", hSalary.ToString());
In some cases, you will type something in the parentheses of ToString().
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.
The System namespace provides a specific letter 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. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. 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 |
Here are examples:
var Distance = 248.38782; var age = 15; var NewColor = 3478; var hSalary = 22.74; var HoursWorked = 35.5018473; var WeeklySalary = hSalary * HoursWorked; Console.WriteLine("Distance: {0}", Distance.ToString("E")); Console.WriteLine("Age: {0}", age.ToString()); Console.WriteLine("Color: {0}", NewColor.ToString("X")); Console.WriteLine("Weekly Salary: {0} for {1} hours", WeeklySalary.ToString("c"), HoursWorked.ToString("F"));
This would produce:
Distance: 2.483878E+002 Age: 15 Color: D96 Weekly Salary: $807.31 for 35.50 hours
As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value.
As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon operator followed by the letter.
Practical Learning: Formatting Data Display
Console.Title = "Georgetown Dry Cleaning Services"; Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine(" Cursomer Order Processing"); Console.WriteLine("========================================"); // Price of items const double priceOneShirt = 1.35; const double priceAPairOfPants = 2.95; const double priceOneDress = 4.55; const double taxRate = 0.0575; // 5.75% // Request customer information from the user // Customer personal infoirmation Console.Write("Enter Customer Name: "); string customerName = Console.ReadLine()!; Console.Write("Enter Customer Phone: "); string homePhone = Console.ReadLine()!; // Request the quantity of each category of items Console.Write("Number of Shirts: "); string strShirts = Console.ReadLine()!; uint numberOfShirts = uint.Parse(strShirts); Console.Write("Number of Pants: "); string strPants = Console.ReadLine()!; uint numberOfPants = uint.Parse(strPants); Console.Write("Number of Dresses: "); string strDresses = Console.ReadLine()!; uint numberOfDresses = uint.Parse(strDresses); // Perform the necessary calculations double subTotalShirts = numberOfShirts * priceOneShirt; double subTotalPants = numberOfPants * priceAPairOfPants; double subTotalDresses = numberOfDresses * priceOneDress; // Calculate the "temporary"total of the order double totalOrder = subTotalShirts + subTotalPants + subTotalDresses; // Calculate the tax amount using a constant rate double taxAmount = totalOrder * taxRate; // Add the tax amount to the total order double salesTotal = totalOrder + taxAmount; // Communicate the total to the user... Console.Write("\nThe Total order is: "); Console.WriteLine(salesTotal.ToString("F")); // and request money for the order Console.Write("Amount Tended? "); double amountTended = double.Parse(Console.ReadLine()!); // Calculate the difference owed to the customer // or that the customer still owes to the store double moneyChange = amountTended - salesTotal; Console.Clear(); // Display the receipt Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-"); Console.WriteLine("===================================="); Console.WriteLine("Customer: {0}", customerName); Console.WriteLine("Home Phone: {0}", homePhone); Console.WriteLine("------------------------------------"); Console.WriteLine("Item Type Qty Unit/Price Sub-Total"); Console.WriteLine("------------------------------------"); Console.WriteLine("Shirts {0} {1:F} {2:C}", numberOfShirts, priceOneShirt, subTotalShirts); Console.WriteLine("Pants {0} {1:F} {2:F}", numberOfPants, priceAPairOfPants, subTotalPants); Console.WriteLine("Dresses {0} {1} {2}", numberOfDresses, priceOneDress.ToString("F"), subTotalDresses.ToString("C")); Console.WriteLine("------------------------------------"); Console.WriteLine("Total Order: {0:C}", totalOrder); Console.WriteLine("Tax Rate: {0:P}", taxRate); Console.WriteLine("Tax Amount: {0}", taxAmount.ToString("C")); Console.WriteLine("Net Price: {0}", salesTotal.ToString("C")); Console.WriteLine("------------------------------------"); Console.WriteLine("Amount Tended: {0:C}", amountTended); Console.WriteLine("Difference: {0}", moneyChange.ToString("C")); Console.WriteLine("========================================");
-/- Georgetown Dry Cleaning Services -/- Cursomer Order Processing ======================================== Enter Customer Name: James Watson Enter Customer Phone: (401) 493-2005 Number of Shirts: 8 Number of Pants: 3 Number of Dresses: 5 The Total order is: 44.84 Amount Tended? 50
-/- Georgetown Dry Cleaning Services -/- ==================================== Customer: James Watson Home Phone: (401) 493-2005 ------------------------------------ Item Type Qty Unit/Price Sub-Total ------------------------------------ Shirts 8 1.35 $10.80 Pants 3 2.95 8.85 Dresses 5 4.55 $22.75 ------------------------------------ Total Order: $42.40 Tax Rate: 5.75% Tax Amount: $2.44 Net Price: $44.84 ------------------------------------ Amount Tended: $50.00 Difference: $5.16 ======================================== Press any key to continue . . .
Line Formatting
In the above programs, to display a line of text, we easily used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can 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 number or the variable in the curly brackets. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:
string fullName = "Anselme Bogos"; int age = 15; double hSalary = 22.74; Console.WriteLine("Full Name: {0,20}", fullName); Console.WriteLine("Age:{0,14}", age.ToString()); Console.WriteLine("Distance: {0:C,8}", hSalary.ToString());
This would produce:
Full Name: Anselme Bogos Age: 15 Distance: 22.74
The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.
Practical Learning: Managing Console Display
namespace StellarWaterPoint3.Models { internal enum Classification { Residential, NonProfit, WaterIntensive, GeneralUse, Other } internal class WaterBill { private readonly string typeOfAccount; public WaterBill(string category) => typeOfAccount = category; public double CounterReadingStart { get; set; } public double CounterReadingEnd { get; set; } public (Classification @class, string name) AccountType { get { if (typeOfAccount == "1") return (Classification.Residential, "Residential Household"); else if (typeOfAccount == "2") return (Classification.NonProfit, "Social/Non-Profit Organization"); else if (typeOfAccount == "3") return (Classification.WaterIntensive, "Water Intensive Business (Laudromat, Hair Salon, etc)"); else if (typeOfAccount == "4") return (Classification.GeneralUse, "General Business, Government"); else return (Classification.Other, "Other"); } } public double Gallons => CounterReadingEnd - CounterReadingStart; public double HCFTotal => Gallons / 748; public (double First25Therms, double Next15Therms, double Above40Therms) Therms { get { double first, next, above; if (HCFTotal is > 40.00) { first = 25.00 * 1.5573; next = 15.00 * 1.2264; above = (HCFTotal - 40.00) * 0.9624; } else if (HCFTotal > 25.00) { first = 25.00 * 1.5573; next = (HCFTotal - 25.00) * 1.2264; above = 0.00; } else // if (HCFTotal > 40.00) { first = HCFTotal * 1.5573; next = 0.00; above = 0.00; } return (first, next, above); } } public double WaterUsageCharges => Therms.First25Therms + Therms.Next15Therms + Therms.Above40Therms; public double SewerCharges { get { double result = AccountType.@class switch { Classification.Residential => WaterUsageCharges * 0.2528, Classification.NonProfit => WaterUsageCharges * 0.0915, Classification.WaterIntensive => WaterUsageCharges * 1.5865, Classification.GeneralUse => WaterUsageCharges * 0.6405, _ => WaterUsageCharges * 1.2125 }; return result; } } public double EnvironmentCharges { get { double result = AccountType.@class switch { Classification.Residential => WaterUsageCharges * 0.0025, Classification.NonProfit => WaterUsageCharges * 0.0015, Classification.WaterIntensive => WaterUsageCharges * 0.0105, Classification.GeneralUse => WaterUsageCharges * 0.0045, _ => WaterUsageCharges * 0.0125 }; return result; } } public double ServiceCharges { get => AccountType.@class switch { Classification.Residential => WaterUsageCharges * 0.0328, Classification.NonProfit => WaterUsageCharges * 0.0115, Classification.WaterIntensive => WaterUsageCharges * 0.1015, Classification.GeneralUse => WaterUsageCharges * 0.0808, _ => WaterUsageCharges * 0.1164 }; } public double TotalCharges => WaterUsageCharges + SewerCharges + EnvironmentCharges + ServiceCharges; public double LocalTaxes { get => AccountType.@class switch { Classification.Residential => TotalCharges * 0.115, Classification.NonProfit => TotalCharges * 0.085, Classification.WaterIntensive => TotalCharges * 0.825, Classification.GeneralUse => TotalCharges * 0.315, _ => TotalCharges * 0.625 }; } public double StateTaxes => AccountType.@class switch { Classification.Residential => TotalCharges * 0.035, Classification.NonProfit => TotalCharges * 0.015, Classification.WaterIntensive => TotalCharges * 0.105, Classification.GeneralUse => TotalCharges * 0.065, _ => TotalCharges * 0.815 }; public double AmountDue => TotalCharges + LocalTaxes + StateTaxes; } }
using StellarWaterPoint3; using static System.Console; WriteLine("Stellar Water Point"); WriteLine("==========================================================="); string ? answer = ""; try { WriteLine("To prepare an invoice, enter the following information"); WriteLine("Types of Accounts"); WriteLine("1. Residential Household"); WriteLine("2. Social/Non-Profit Organization"); WriteLine("3. Water Intensive Business (Laudromat, etc)"); WriteLine("4. General Business"); WriteLine("0. Other"); Write("Enter Type of Account: "); answer = ReadLine()!; WriteLine("-----------------------------------------------------------"); } catch(FormatException fe) { WriteLine("There was an error from the request for the account type was presented." + Environment.NewLine + "The error produced was: " + fe.Message); WriteLine("-----------------------------------------------------------"); } Clear(); WaterBill bill = new WaterBill(answer); if (bill != null) { WriteLine("==========================================================="); WriteLine("Stellar Water Point - Customer Invoice"); WriteLine("Account Type: {0}", bill.AccountType.name); WriteLine("==========================================================="); try { Write("Counter Reading Start: "); bill.CounterReadingStart = int.Parse(ReadLine()!); } catch (FormatException fe) { WriteLine("There was an error from the request for the counter starting number was made." + Environment.NewLine + "The error produced was: " + fe.Message); WriteLine("-----------------------------------------------------------"); } try { Write("Counter Reading End: "); bill.CounterReadingEnd = int.Parse(ReadLine()!); } catch (FormatException fe) { WriteLine("There was an error from the request for the counter ending number was made." + Environment.NewLine + "The error produced was: " + fe.Message); WriteLine("-----------------------------------------------------------"); } Clear(); if ((answer != "") && (bill.CounterReadingStart != 0) && (bill.CounterReadingEnd != 0)) { WriteLine("==========================================================="); WriteLine("Stellar Water Point - Customer Invoice"); WriteLine("Account Type: {0}", bill.AccountType.name); WriteLine("==========================================================="); WriteLine("Meter Reading"); WriteLine("-----------------------------------------------------------"); WriteLine("Counter Reading Start: {0,10}", bill.CounterReadingStart); WriteLine("Counter Reading End: {0,10}", bill.CounterReadingEnd); WriteLine("Total Gallons Consumed: {0,10}", bill.Gallons); WriteLine("==========================================================="); WriteLine("Therms Evaluation"); WriteLine("-----------------------------------------------------------"); WriteLine("HCF Total: {0,10:n}", bill.HCFTotal); WriteLine("First 35 Therms (* 1.5573): {0,10:n}", bill.Therms.First25Therms); WriteLine("First 20 Therms (* 1.2264): {0,10:n}", bill.Therms.Next15Therms); WriteLine("Above 40 Therms (* 0.9624): {0,10:n}", bill.Therms.Above40Therms); WriteLine("-----------------------------------------------------------"); WriteLine("Water Usage Charges: {0,10:n}", bill.WaterUsageCharges); WriteLine("Sewer Charges: {0,10:n}", bill.SewerCharges); WriteLine("==========================================================="); WriteLine("Bill Values"); WriteLine("-----------------------------------------------------------"); WriteLine("Environment Charges: {0,10:n}", bill.EnvironmentCharges); WriteLine("Service Charges: {0,10:n}", bill.ServiceCharges); WriteLine("Total Charges: {0,10:n}", bill.TotalCharges); WriteLine("Local Taxes: {0,10:n}", bill.LocalTaxes); WriteLine("State Taxes: {0,10:n}", bill.StateTaxes); WriteLine("-----------------------------------------------------------"); WriteLine("Amount Due: {0,10:n}", bill.AmountDue); } else { WriteLine("==========================================================="); WriteLine("The water bill was not prepared appropriately."); } } Write("===========================================================");
=========================================================== Stellar Water Point - Customer Invoice Account Type: Residential Household =========================================================== Counter Reading Start:
=========================================================== Stellar Water Point - Customer Invoice Account Type: Residential Household =========================================================== Counter Reading Start: 137926 Counter Reading End: 188420
=========================================================== Stellar Water Point - Customer Invoice Account Type: Residential Household =========================================================== Meter Reading ----------------------------------------------------------- Counter Reading Start: 137926 Counter Reading End: 188420 Total Gallons Consumed: 50494 =========================================================== Therms Evaluation ----------------------------------------------------------- HCF Total: 67.51 First 35 Therms (* 1.5573): 38.93 First 20 Therms (* 1.2264): 18.40 Above 40 Therms (* 0.9624): 26.47 ----------------------------------------------------------- Water Usage Charges: 83.80 Sewer Charges: 21.18 =========================================================== Bill Values ----------------------------------------------------------- Environment Charges: 0.21 Service Charges: 2.75 Total Charges: 107.94 Local Taxes: 12.41 State Taxes: 3.78 ----------------------------------------------------------- Amount Due: 124.13 =========================================================== Press any key to close this window . . .
|
|||
Previous | Copyright © 2001-2023, FunctionX | Saturday 04 June 2022 | Next |
|