Home

Data Reading and Formatting

 

Data Reading

 

Introduction

In previous lessons, we saw that the Console class allowed using Write() and WriteLine() to display things on the screen. While Console.Write() is used to display something on the screen, you can use Console. Read() 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. You can use Read() to wait for the user to press any key in order to close the DOS window.

Besides Console.Read(), you can use Console.ReadLine(). Like Console.WriteLine(), after performing its assignment, Console.ReadLine() sends the caret to the next line. Otherwise, it plays the same role as Console.Read().

Practical LearningPractical Learning: Introducing Data Reading

  1. Start Notepad and type the following:
     
    package GCS;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    
    	}
    }
  2. Save the file in a new folder named GCS2 inside your JSharp Lessons folder
  3. Save the file as Exercise.jsl in the GCS1 folder

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 Console.Read() or Console.ReadLine() and assign it to the name of the variable whose value you want to retrieve. Here is an example:

package Exercise1;
import System.*;

public class Class1
{
	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 file as follows:
     
    package GCS;
    import System.*;
    
    public class Exercise
    {
    	public 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 application. Here is an example:
     
    -/- 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. Return to Notepad

Number Request

In a program, 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:

package Exercise1;
import 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 used by J# has an equivalent class. The equivalent class is equipped with a function that performs the conversion. Based on this, if you declare your variable using the int data type, its corresponding class is Integer, and the Integer class is equipped with parseInt(). To use parseInt(), type the data type, followed by a period, followed by parseInt(). In the parentheses of parseInt(), type the string that you requested from the user. Here is an example:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		int number;
		String strNumber;

		strNumber = Console.ReadLine();
		number = Integer.parseInt(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:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		int number;
		String strNumber;

		number = Integer.parseInt(Console.ReadLine());
	}
}

After getting the number, you can use it as you see fit. For example, you can display it to the user. Here is an example:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		int number;
		String strNumber;

		Console.Write("Enter a natural number: ");
		strNumber = Console.ReadLine();
		number = Integer.parseInt(strNumber);
		Console.WriteLine("Number: " + number);
	}
}

Here is an example of running the program:

Enter a natural number: 2844
Number: 2844
Press any key to continue

While you can use Integer.parseInt() to convert a string value to a natural number, each of the other data types also has its equivalent class and that class is equipped with its conversion method.

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
     
    package GCS1;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		// Price of items
    		final double priceOneShirt     = 0.95D;
    		final double priceAPairOfPants = 2.95D;
    		final double priceOneDress     = 4.55D;
    		final double taxRate           = 0.0575D;  // 5.75%
    
    		// Customer personal information
    		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, 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   = Integer.parseInt(strShirts);
    			
    		Console.Write("Number of Pants:   ");
    		String strPants  = Console.ReadLine();
    		numberOfPants    = Integer.parseInt(strPants);
    			
    		Console.Write("Number of Dresses: ");
    		String strDresses = Console.ReadLine();
    		NumberOfDresses   = Integer.parseInt(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    = Double.parseDouble(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. Execute the application. Here is an example of running the program:
     
    -/- 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: 4
    
    The Total order is: 33.52275
    Amount Tended? 50
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   Genevieve Alton
    Home Phone: (202) 974-8244
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      8     0.95     7.6
    Pants       2     2.95     5.9
    Dresses     4     4.55     18.2
    ------------------------------------
    Total Order:     31.7
    Tax Rate:        5.75%
    Tax Amount:      1.82275
    Net Price:       33.52275
    ------------------------------------
    Amount Tended:   50
    difference:      16.47725
    ====================================
    Press any key to continue
  3. Return to Notepad
 

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:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		String strDateHired;

		Console.Write("Enter a date: ");
		strDateHired = Console.ReadLine();
	}
}

After getting a date (or a time value) as a string from the user, in order to use as such, you must first 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. Here is an example:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		String strDateHired;

		Console.Write("Enter a date (mm/dd/yyyy): ");
		strDateHired = Console.ReadLine();
	}
}

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:
     
    package GCS1;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		// Price of items
    		final double priceOneShirt     = 0.95D;
    		final double priceAPairOfPants = 2.95D;
    		final double priceOneDress     = 4.55D;
    		final double taxRate           = 0.0575D;  // 5.75%
    
    		// Customer personal information
    		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, 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();
    		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   = Integer.parseInt(strShirts);
    			
    		Console.Write("Number of Pants:   ");
    		String strPants  = Console.ReadLine();
    		numberOfPants    = Integer.parseInt(strPants);
    			
    		Console.Write("Number of Dresses: ");
    		String strDresses = Console.ReadLine();
    		NumberOfDresses   = Integer.parseInt(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    = Double.parseDouble(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 application. Here is an example of running the program:
     
    -/- 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

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 referred to as 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, etc. With this technique, you can create the string anyway you like and use the placeholders anywhere inside of 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 values for each one of them in this second part, separating the values with a comma. 

Here is an example:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		String fullName = "Anselme Bogos";
		int age = 15;
		double hourlySalary = 22.74;

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

This would produce:

Full Name: Anselme Bogos

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.

Value Casting

If the value you are providing for a placeholder is a string, you can just provide it. If it is not a string, you must cast it to the appropriate type. Here is an example:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		String fullName = "Anselme Bogos";
		int age = 15;
		double hourlySalary = 22.74;

		Console.WriteLine("Full Name: {0}",  fullName);
		Console.WriteLine("Age: {0}", (System.Int32)age);
		Console.WriteLine("Salary: {0}", (System.Double)hourlySalary);
	}
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Salary: 22.74

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

Here is an example:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		String fullName = "Anselme Bogos";
		int age = 15;
		double hourlySalary = 22.74;

		Console.WriteLine("Full Name: {0}\nAge: {1}\nSalary: {2}",
			         fullName, (System.Int32)age,
			         (System.Double)hourlySalary);
	}
}
 

Practical LearningPractical Learning: Displaying Data With Placeholders

  1. To use curly brackets to display data, change the file as follows:
     
    package GCS1;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		// Price of items
    		final double priceOneShirt     = 0.95D;
    		final double priceAPairOfPants = 2.95D;
    		final double priceOneDress     = 4.55D;
    		final double taxRate           = 0.0575D;  // 5.75%
    
    		// Customer personal information
    		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, 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();
    		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   = Integer.parseInt(strShirts);
    			
    		Console.Write("Number of Pants:   ");
    		String strPants  = Console.ReadLine();
    		numberOfPants    = Integer.parseInt(strPants);
    			
    		Console.Write("Number of Dresses: ");
    		String strDresses = Console.ReadLine();
    		NumberOfDresses   = Integer.parseInt(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: {0}", (System.Double)salesTotal);
    		// and request money for the order
    		Console.Write("Amount Tended? ");
    		amountTended    = Double.parseDouble(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.WriteLine("Customer:    {0}", customerName);
    		Console.WriteLine("Home Phone:  {0}", homePhone);
    		Console.WriteLine("Date & Time: {0}", orderDate);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Shirts      {0}     {1}     {2}",
    						 (System.Int32)numberOfShirts,
    			             (System.Double)priceOneShirt,
    			             (System.Double)subTotalShirts);
    		Console.WriteLine("Pants       {0}     {1}     {2}",
    			             (System.Int32)numberOfPants,
    			             (System.Double)priceAPairOfPants,
    			             (System.Double)subTotalPants);
    		Console.WriteLine("Dresses     {0}     {1}     {2}",
    			             (System.Int32)NumberOfDresses,
    			             (System.Double)priceOneDress,
    			             (System.Double)subTotalDresses);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Total Order:     {0}", (System.Double)totalOrder);
    		Console.WriteLine("Tax Rate:        {0}%", (System.Double)(taxRate * 100));
    		Console.WriteLine("Tax Amount:      {0}", (System.Double)taxAmount);
    		Console.WriteLine("Net Price:       {0}", (System.Double)salesTotal);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Amount Tended:   {0}", (System.Double)amountTended);
    		Console.WriteLine("difference:      {0}", (System.Double)difference);
    		Console.WriteLine("====================================");
    	}
    }
  2. Save, compile, and execute the program

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, depending on the circumstance, you may prefer to show it as a hexadouble value. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of the double separator and in some cases, you may want to display a salary with only 2 double 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 Used For
  c C Currency values
  d D Double numbers
  e E Scientific numeric display such as 1.45e5
  f F Fixed double numbers
  g G General and most common type of numbers
  n N Natural numbers
  r R Roundtrip formatting
  x X Hexadouble formatting
  p P Percentages

Here are examples:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		double distance = 248.38782;
		int age = 15;
		long color = 3478;
		double hourlySalary = 22.74, hoursWorked = 35.5018473;
		double weeklySalary = hourlySalary * hoursWorked;

		Console.WriteLine("Distance: {0:E}", (System.Double)distance);
		Console.WriteLine("Age: {0}", (System.Int32)age);
		Console.WriteLine("Color: {0:X}", (System.Int32)color);
		Console.WriteLine("Weekly Salary: {0:C} for {1:F} hours",
			(System.Double)weeklySalary, (System.Double)hoursWorked);
	}
}

This would produce:

Distance: 2.483878E+002
Age: 15
Color: D96
Weekly Salary: $807.31 for 35.50 hours
Press any key to continue

As you may have noticed, if you don't use a specific format, the compiler would use a default formatting to display the value.

Instead of passing the format(s) to Console.Write() or Console.WriteLine(), the .NET Framework provides the String class. To use this class, type the following: String.Format(). In the parentheses, provide the same formats we have used above. After using String.Format(), it produces a string you can pass to Console.Write() or Console.WriteLine(). Here are examples:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		double distance = 248.38782;
		int age = 15;
		long color = 3478;
		double hourlySalary = 22.74, hoursWorked = 35.5018473;
		double weeklySalary = hourlySalary * hoursWorked;

		String strDistance  = String.Format("{0:E}", (System.Double)distance);
		String strAge       = String.Format("{0}", (System.Int32)age);
		String strColor     = String.Format("{0:X}", (System.Int32)color);
		String strWeekly    = String.Format("{0:C} for {1:F} hours",
               			                 (System.Double)weeklySalary,
			                          (System.Double)hoursWorked);

		Console.WriteLine("Distance: {0}", strDistance);
		Console.WriteLine("Age: {0}", strAge);
		Console.WriteLine("Color: {0}", strColor);
		Console.WriteLine("Weekly Salary: {0}", strWeekly);
	}
}
 

Practical LearningPractical Learning: Formatting Data Display

  1. To format data display, change the file as follows:
     
    package GCS1;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		// Price of items
    		final double priceOneShirt     = 0.95D;
    		final double priceAPairOfPants = 2.95D;
    		final double priceOneDress     = 4.55D;
    		final double taxRate           = 0.0575D;  // 5.75%
    
    		// Customer personal information
    		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, 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();
    		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   = Integer.parseInt(strShirts);
    			
    		Console.Write("Number of Pants:   ");
    		String strPants  = Console.ReadLine();
    		numberOfPants    = Integer.parseInt(strPants);
    			
    		Console.Write("Number of Dresses: ");
    		String strDresses = Console.ReadLine();
    		NumberOfDresses   = Integer.parseInt(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: {0:C}", (System.Double)salesTotal);
    		// and request money for the order
    		Console.Write("Amount Tended? ");
    		amountTended    = Double.parseDouble(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.WriteLine("Customer:    {0}", customerName);
    		Console.WriteLine("Home Phone:  {0}", homePhone);
    		Console.WriteLine("Date & Time: {0}", orderDate);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Shirts      {0}     {1:C}     {2:C}",
    			        (System.Int32)numberOfShirts,
    			        (System.Double)priceOneShirt,
    			        (System.Double)subTotalShirts);
    		Console.WriteLine("Pants       {0}     {1:C}     {2:C}",
    			        (System.Int32)numberOfPants,
    			        (System.Double)priceAPairOfPants,
    			        (System.Double)subTotalPants);
    		Console.WriteLine("Dresses     {0}     {1:C}     {2:C}",
    			        (System.Int32)NumberOfDresses,
    			        (System.Double)priceOneDress,
    			        (System.Double)subTotalDresses);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Total Order:     {0:C}", (System.Double)totalOrder);
    		Console.WriteLine("Tax Rate:        {0:F}%", (System.Double)(taxRate * 100));
    		Console.WriteLine("Tax Amount:      {0:C}", (System.Double)taxAmount);
    		Console.WriteLine("Net Price:       {0:C}", (System.Double)salesTotal);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Amount Tended:   {0:C}", (System.Double)amountTended);
    		Console.WriteLine("difference:      {0:C}", (System.Double)difference);
    		Console.WriteLine("====================================");
    	}
    }
  2. Save it and switch to the Command Prompt. Then compile the file and execute the application. Here is an example:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Gretchen McCormack
    Enter Customer Phone: (410) 739-2884
    Enter the order date and time (mm/dd/yyyy hh:mm AM/PM)
    04/09/2001 10:25 AM
    Number of Shirts:  5
    Number of Pants:   12
    Number of Dresses: 8
    
    The Total order is: 80.951625
    Amount Tended? 100
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Gretchen McCormack
    Home Phone:  (410) 739-2884
    Date & Time: 4/9/2001 10:25:00 AM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     $0.95     $4.75
    Pants       12    $2.95     $35.40
    Dresses     8     $4.55     $36.40
    ------------------------------------
    Total Order:     $76.55
    Tax Rate:        5.75 %
    Tax Amount:      $4.40
    Net Price:       80.95
    ------------------------------------
    Amount Tended:   $100.00
    difference:      $19.05
    ====================================
  3. Return to Notepad

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 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 placer and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

package Exercise1;
import System.*;

public class Exercise
{
	public static void main()
	{
		String fullName = "Anselme Bogos";
		int age = 15;
		double hourlySalary = 22.74;

		Console.WriteLine("Full Name: {0,20}", fullName);
		Console.WriteLine("Age:{0,14}", (System.Int32)age);
		Console.WriteLine("Salary: {0:C,8}", (System.Double)hourlySalary);
	}
}

This would produce:

Full Name:        Anselme Bogos
Age:            15
Salary: C8
Press any key to continue

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.

Data and Time Formatting

As mentioned earlier, when the user enters a date value for a DateTime variable, the compiler adds a time part to the value. Fortunately, if you want to consider only the date or only the time part, you can specify this to the compiler. To support this, the DateTime data type provides a series of letters you can use to format how its value should be displayed to the user. The character is entered in the placeholder of the DateTime variable after the 0 or the incremental numeric value.

Practical LearningPractical Learning: Controlling Date/Time Formatting

  1. To control formatting of date and time, change the file as follows:
     
    package GCS1;
    import System.*;
    
    public class Exercise
    {
    	public static void main()
    	{
    		// Price of items
    		final double priceOneShirt     = 0.95D;
    		final double priceAPairOfPants = 2.95D;
    		final double priceOneDress     = 4.55D;
    		final double taxRate           = 0.0575D;  // 5.75%
    
    		// Customer personal information
    		String customerName, homePhone;
    		DateTime 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, 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();
    		Console.Write("Enter the order date(mm/dd/yyyy):  ");
    		orderDate = DateTime.Parse(Console.ReadLine());
    		Console.Write("Enter the order time(hh:mm AM/PM): ");
    		orderTime = DateTime.Parse(Console.ReadLine());
    			
    		// Request the quantity of each category of items
    		Console.Write("Number of Shirts:  ");
    		String strShirts = Console.ReadLine();
    		numberOfShirts   = Integer.parseInt(strShirts);
    			
    		Console.Write("Number of Pants:   ");
    		String strPants  = Console.ReadLine();
    		numberOfPants    = Integer.parseInt(strPants);
    			
    		Console.Write("Number of Dresses: ");
    		String strDresses = Console.ReadLine();
    		NumberOfDresses   = Integer.parseInt(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.WriteLine("\nThe Total order is: {0:C}", (System.Double)salesTotal);
    		// and request money for the order
    		Console.Write("Amount Tended? ");
    		amountTended    = Double.parseDouble(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.WriteLine("Customer:    {0}", customerName);
    		Console.WriteLine("Home Phone:  {0}", homePhone);
    		Console.WriteLine("Order Date:  {0:D}", orderDate);
    		Console.WriteLine("Order Time:  {0:t}", orderTime);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Shirts      {0}     {1:C}     {2:C}",
    						 (System.Int32)numberOfShirts,
    			             (System.Double)priceOneShirt,
    			             (System.Double)subTotalShirts);
    		Console.WriteLine("Pants       {0}     {1:C}     {2:C}",
    			             (System.Int32)numberOfPants,
    			             (System.Double)priceAPairOfPants,
    			             (System.Double)subTotalPants);
    		Console.WriteLine("Dresses     {0}     {1:C}     {2:C}",
    			             (System.Int32)NumberOfDresses,
    			             (System.Double)priceOneDress,
    			             (System.Double)subTotalDresses);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Total Order:     {0:C}", (System.Double)totalOrder);
    		Console.WriteLine("Tax Rate:        {0:F}%", (System.Double)(taxRate * 100));
    		Console.WriteLine("Tax Amount:      {0:C}", (System.Double)taxAmount);
    		Console.WriteLine("Net Price:       {0:C}", (System.Double)salesTotal);
    		Console.WriteLine("------------------------------------");
    		Console.WriteLine("Amount Tended:   {0:C}", (System.Double)amountTended);
    		Console.WriteLine("difference:      {0:C}", (System.Double)difference);
    		Console.WriteLine("====================================");
    	}
    }
  2. Save, compile, and run the program. Here is an example:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Antoinette Calhoun
    Enter Customer Phone: (703) 797-1135
    Enter the order date(mm/dd/yyyy):  04/12/2002
    Enter the order time(hh:mm AM/PM): 2:12 PM
    Number of Shirts:  5
    Number of Pants:   2
    Number of Dresses: 1
    
    The Total order is: $16.07
    Amount Tended? 20
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Antoinette Calhoun
    Home Phone:  (703) 797-1135
    Order Date:  Friday, April 12, 2002
    Order Time:  2:12 PM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts     5   $0.95       $4.75
    Pants      2   $2.95        $5.90
    Dresses    1   $4.55        $4.55
    ------------------------------------
    Total Order:   $15.20
    Tax Rate:      5.75 %
    Tax Amount:    $0.87
    Net Price:     $16.07
    ------------------------------------
    Amount Tended: $20.00
    difference:    $3.93
    ====================================
  3. Type Exit and close Notepad

Previous Copyright © 2005 FunctionX, Inc. Next