Data Reading and Formatting

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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 Learning: Introducing Data Reading

Start Notepad and type the following:

package GCS;
import System.*;

public class Exercise
{
	public static void main()
	{

	}
}

Save the file in a new folder named GCS2 inside your JSharp Lessons folder

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 Learning: Reading String Values

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("====================================
");
	}
}

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
====================================
  1. 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 Learning: Reading Numeric Values

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("
The 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("====================================");
	}
}

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

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 Learning: Requesting Date and Time Values

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("
The 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("====================================");
	}
}

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
====================================

Return to Notepad