Home

Data Reading

 

Introduction

In previous lessons, we saw that the Console class allows using the Write() and the WriteLine() methods to display things on the screen. While the Console.Write() method is used to display something on the screen, the Console class provides the Read() method to get a value from the user. To use it, the name of a variable can be assigned to it. The syntax used is:

VariableName = 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# (even including Microsoft's C# and Borland C#Builder) would 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.

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

 

Practical LearningPractical Learning: Introducing Data Reading

  1. Start Microsoft Visual C# and create a Console Application named GeorgetownCleaningServices3
  2. Change the file type as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices3
    {
        class OrderProcessing
        {
    	static void Main()
    	{
    	    Console.WriteLine();
    	}
        }
    }
  3. Save the file

String Value Request 

In most assignments of your programs, you will not know the value of a string when writing your application. For example, 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:

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 file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices3
    {
        class OrderProcessing
        {
    	static void Main()
    	{
    	    string CustomerName, HomePhone;
    
    	    Console.WriteLine("-/- Georgetown 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.WriteLine();
    	    // Display the receipt
    	    Console.WriteLine("====================================");
    	    Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    	    Console.WriteLine("====================================");
    	    Console.Write("Customer:   ");
    	    Console.WriteLine(CustomerName);
    	    Console.Write("Home Phone: ");
    	    Console.WriteLine(HomePhone);
    	    Console.WriteLine("====================================\n");
    	}
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  James Watson
    Enter Customer Phone: (410) 493-2005
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Watson
    Home Phone: (410) 493-2005
    ====================================
  3. Close the DOS window

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;

namespace GeorgetownCleaningServices3
{
	class OrderProcessing
	{
		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;

namespace GeorgetownCleaningServices3
{
	class OrderProcessing
	{
		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;

namespace GeorgetownCleaningServices3
{
	class OrderProcessing
	{
		static void Main()
		{
			int Number;

			Number = int.Parse(Console.ReadLine());
		}
	}
}

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices3
    {
        class OrderProcessing
        {
    	static void Main()
    	{
    	    // Price of items
    	    const decimal PriceOneShirt     = 0.95M;
    	    const decimal PriceAPairOfPants = 2.95M;
    	    const decimal PriceOneDress     = 4.55M;
    	    const decimal TaxRate           = 0.0575M;  // 5.75%
    
    	    // Customer personal infoirmation
    	    string CustomerName, HomePhone;
    	    // Unsigned numbers to represent cleaning items
    	    uint NumberOfShirts, NumberOfPants, NumberOfDresses;
    	    // Each of these sub totals will be used for cleaning items
    	    decimal SubTotalShirts, SubTotalPants, SubTotalDresses;
    	    // Values used to process an order
    	    decimal TotalOrder, TaxAmount, SalesTotal;
    	    decimal AmountTended, Difference;
    
    	    Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    	    // Request customer information from the user
    	    Console.Write("Enter Customer Name:  ");
    	    CustomerName = Console.ReadLine();
    	    Console.Write("Enter Customer Phone: ");
    	    HomePhone = Console.ReadLine();
    			
    	    // Request the quantity of each category of items
    	    Console.Write("Number of Shirts:  ");
    	    string strShirts = Console.ReadLine();
    	    NumberOfShirts   = uint.Parse(strShirts);
    			
    	    Console.Write("Number of Pants:   ");
    	    string strPants  = Console.ReadLine();
    	    NumberOfPants    = uint.Parse(strPants);
    			
    	    Console.Write("Number of Dresses: ");
    	    string strDresses = Console.ReadLine();
    	    NumberOfDresses   = uint.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...
    	    Console.Write("\nThe Total order is: ");
    	    Console.WriteLine(SalesTotal);
    	    // and request money for the order
    	    Console.Write("Amount Tended? ");
    	    AmountTended    = decimal.Parse(Console.ReadLine());
    
    	    // Calculate the difference owed to the customer
    	    // or that the customer still owes to the store
    	    Difference      = AmountTended - SalesTotal;
    	    Console.WriteLine();
    
    	    // Display the receipt
    	    Console.WriteLine("====================================");
    	    Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    	    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(Difference);
    	    Console.WriteLine("====================================");
    	}
        }
    }
  2. Eo execute the program and test it. Here is an example:
     
    -/- Georgetown 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
    
    ====================================
    -/- Georgetown 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
    ====================================
  3. Close the DOS window

Requesting Dates and Times

As done with the regular numbers, you can request a date value from the user. This is also done by requesting a string from the user. Here is an example:

using System;

namespace ValueRequests
{
	class Exercise
	{
		static void Main()
		{
			string strDateHired;

			strDateHired = Console.ReadLine();
		}
	}
}

After the user has entered the string you can then convert it to a DateTime value. Just like any value you request from the user, a date or time value that the user types must be valid, otherwise, the program would produce an error. Because dates and times follow some rules for their formats, you should strive to let the user know how you expect the value to be entered.

By default, if you request only a date from the user and the user enters a valid date, the compiler would add the midnight value to the date. If you request only the time from the user and the user enters a valid time, the compiler would add the current date to the value. Later on, we will learn how to isolate either only the date or only the time.

Practical LearningPractical Learning: Requesting Date and Time Values

  1. To deal with new dates and times, change the program as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices3
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			// Price of items
    			const decimal PriceOneShirt     = 0.95M;
    			const decimal PriceAPairOfPants = 2.95M;
    			const decimal PriceOneDress     = 4.55M;
    			const decimal TaxRate           = 0.0575M;  // 5.75%
    
    			// Basic information about an order
    			string CustomerName, HomePhone;
    			DateTime OrderDate;
    			// Unsigned numbers to represent cleaning items
    			uint NumberOfShirts, NumberOfPants, NumberOfDresses;
    			// Each of these sub totals will be used for cleaning items
    			decimal SubTotalShirts, SubTotalPants, SubTotalDresses;
    			// Values used to process an order
    			decimal TotalOrder, TaxAmount, SalesTotal;
    			decimal AmountTended, Difference;
    
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			// Request order information from the user
    			Console.Write("Enter Customer Name:  ");
    			CustomerName = Console.ReadLine();
    			Console.Write("Enter Customer Phone: ");
    			HomePhone = Console.ReadLine();
    			Console.WriteLine("Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)");
    			OrderDate = DateTime.Parse(Console.ReadLine());
    			
    			// Request the quantity of each category of items
    			Console.Write("Number of Shirts:  ");
    			string strShirts = Console.ReadLine();
    			NumberOfShirts   = uint.Parse(strShirts);
    			
    			Console.Write("Number of Pants:   ");
    			string strPants  = Console.ReadLine();
    			NumberOfPants    = uint.Parse(strPants);
    			
    			Console.Write("Number of Dresses: ");
    			string strDresses = Console.ReadLine();
    			NumberOfDresses   = uint.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...
    			Console.Write("\nThe Total order is: ");
    			Console.WriteLine(SalesTotal);
    			// and request money for the order
    			Console.Write("Amount Tended? ");
    			AmountTended    = decimal.Parse(Console.ReadLine());
    
    			// Calculate the difference owed to the customer
    			// or that the customer still owes to the store
    			Difference      = AmountTended - SalesTotal;
    			Console.WriteLine();
    
    			// Display the receipt
    			Console.WriteLine("====================================");
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			Console.WriteLine("====================================");
    			Console.Write("Customer:    ");
    			Console.WriteLine(CustomerName);
    			Console.Write("Home Phone:  ");
    			Console.WriteLine(HomePhone);
    			Console.Write("Date & Time: ");
    			Console.WriteLine(OrderDate);
    			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(Difference);
    			Console.WriteLine("====================================");
    		}
    	}
    }
  2. Execute the program and test it. Here is an example:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Alexander Pappas
    Enter Customer Phone: (301) 397-9764
    Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)
    06/22/98 08:26 AM
    Number of Shirts:  2
    Number of Pants:   6
    Number of Dresses: 0
    
    The Total order is: 20.727000
    Amount Tended? 50
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Alexander Pappas
    Home Phone:  (301) 397-9764
    Date & Time: 6/22/1998 8:26:00 AM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      2     0.95     1.90
    Pants       6     2.95     17.70
    Dresses     0     4.55     0
    ------------------------------------
    Total Order:     19.60
    Tax Rate:        5.7500%
    Tax Amount:      1.127000
    Net Price:       20.727000
    ------------------------------------
    Amount Tended:   50
    Difference:      29.273000
    ====================================
  3. Return to Notepad

Previous Copyright © 2006-2016, FunctionX, Inc. Next