Home

Data Reading and Writing

 

Data Request

 

Introduction

Many of the values used in your program simply allow you to display them to the user. In some cases, you may want to request values from the user. As we saw in the previous lesson, there are various types of values you would need the user to supply. Some times the user will clearly understand your request. Some times either your request will not be clear or the user would be playing with the program. In other words, many things can go wrong. To anticipate this, Java, like many other languages, provides some mechanisms to handle errors. This is referred to as Exception Handling, which we will review in details in other lessons. For now, consider that Java is aware of various bad things that could happen while your program is running and the language is equipped to assist you.

Before requesting a value from the user, you can ask the compiler to take care of any bad behavior on your behalf. To do this, on the right side of the line that contains the main() function, type throws Exception (in future lessons, many of these things will become clear). This would be done as follows:

public static void main(String[] args) throws Exception

The Exception class is defined in the io package. Therefore, before using it, import it to your program. This results in the following:

package exercise1;
import java.io.*;

public class Main {

    public static void main(String[] args) throws Exception {
      
    }
}

This informs the compiler that you are aware that the program may generate an error (called exception).

String Request

Before requesting a value from the user, you must create an object that will handle the transaction(s) between the user and the computer. To do this, you would declare a variable of type BufferedReader and initialize it using the following formula:

BufferedReader request = new BufferedReader(new InputStreamReader(System.in));

In this formula, you can replace request with any valid variable name of your choice.

After declaring the BufferedReader variable, you can use its methods to perform the necessary operations. One of these operations consists of requesting a value from the user. To support this, the BufferedReader class is equipped with the readLine() method that would read whatever value the user would type. The value read can be assigned to a String variable of your choice. Here is an example:

public static void main(String[] args) throws Exception
{
        // TODO code application logic here
        BufferedReader request = new BufferedReader(new InputStreamReader(System.in));
        
        System.out.print("Enter Full Name: ");
        String fullName = request.readLine();    
}

After reading the value, it gets stored in the variable and you can use it as you see fit. For example, you can display it by passing the name of the variable to the print() or the println() methods of the out class. Here is an example:

package Exercise2;
import java.io.*;

public class Exercise {
    public static void main(String[] args) throws Exception
    {
        BufferedReader request = new BufferedReader(new InputStreamReader(System.in));
        
        System.out.print("Enter Full Name: ");
        String fullName = request.readLine();
        System.out.println("Full Name: " + fullName);
    }
}

Here is an example of running the program:

Enter Full Name: Patrick Ondo
Full Name: Patrick Ondo
 

Practical LearningPractical Learning: Reading String Values

  1. Start the NetBeans IDE
  2. On the main menu, click File -> New Project...
  3. In the first page of the wizard, click General. In the Projects list, make sure that Java Application is selected and click Next
  4. In the Project Location, accept the suggested path or type a new one, such as C:\Programs\JavaLessons.
    In the Project Name text box, type GCS1 for a new application and click Finish
  5. Make changes to the file so it appears as follows:
     
    package Exercise;
    import java.io.*;
    
    public class Exercise {
    
        public static void main(String[] args) throws Exception
        {
            	BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            	String CustomerName, HomePhone;
    
    	System.out.println("-/- Georgetown Cleaning Services -/-");
    	// Request customer information from the user
    	System.out.print("Enter Customer Name:  ");
    	CustomerName = reader.readLine();
    	System.out.print("Enter Customer Phone: ");
    	HomePhone = reader.readLine();
    
    	// Display the receipt
    	System.out.println("====================================");
    	System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("====================================");
    	System.out.println("Customer:   " + CustomerName);
    	System.out.println("Home Phone: " + HomePhone);
    	System.out.println("=================================");
        }  
    }
  6. Execute the program
  7. Enter the values requested. 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
    =================================
  8. Return to the text editor
 

Data Request

 

Introduction

When you decide to request some values from the user, by default, anything the user types is considered a string. Before getting a non-string value involved in any calculation, you can first request it as a string. Here is an example:

/* Exercise.java */

package Exercise5;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        	BufferedReader jin = new BufferedReader(new InputStreamReader(System.in));
        
	String strNumber;

        	System.out.print("Enter a Number: ");
	strNumber = jin.readLine();
    }
}

After getting the string, you must convert it to the desired value. 

 

Number Request

Once you have gotten a string from the user, if you intend to use it as a numeric value, you should convert. To perform this conversion, each data type provides an appropriate method. To use it, type the name of the data type's class as we introduced them in the previous lesson, followed by a period, followed by the method, and followed by parentheses. In the parentheses, type the string that you requested from the user.

To convert a value to an int, use the parseInt() method of the Integer class. Here is an example:

/* Exercise.java */

package Exercise5;
import java.io.*;

public class Exercise
{
    public static void main(String[] args) throws Exception
    {
        BufferedReader jin = new BufferedReader(new InputStreamReader(System.in));
        int Number;
        String strNumber;

        System.out.print("Enter a Number: ");
        strNumber = jin.readLine();
        Number = Integer.parseInt(strNumber);
        
        System.out.print("Number: " + Number);
    }
}

In the same way, to convert a value to double, use Double.parseDouble().

If the conversion is successful, it produces a natural number. If the conversion is not successful, the compiler would produce (throw) an error (exception).

 

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
    	final double priceOneShirt     = 0.95D;
    	final double priceAPairOfPants = 2.95D;
    	final double priceOneDress     = 4.55D;
    	final double salesTaxRate      = 0.0575D; // 5.75%
    
    	String customerName = "James Burreck",
    	       homePhone = "(202) 301-7030";
    	int numberOfShirts   = 5,
                numberOfPants    = 2,
    	    numberOfDresses  = 3;
    	int totalNumberOfItems;
    	double subTotalShirts, subTotalPants, subTotalDresses;
    	double taxAmount, totalOrder, netPrice;
    	int orderMonth = 3, orderDay = 15, OrderYear = 2002;
    
    	totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
    	subTotalShirts  = priceOneShirt * numberOfShirts;
    	subTotalPants   = priceAPairOfPants * numberOfPants;
    	subTotalDresses = numberOfDresses * priceOneDress;
    	totalOrder      = subTotalShirts + subTotalPants + subTotalDresses;
    	taxAmount       = totalOrder * salesTaxRate / 100;
    	netPrice  = totalOrder - taxAmount;
    
    	System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("====================================");
    	System.out.println("Customer:   " + customerName);
    	System.out.println("Home Phone: " + homePhone);
    	System.out.print("Order Date: ");
    	System.out.print(orderMonth);
    	System.out.print('/');
    	System.out.print(orderDay);
    	System.out.print('/');
    	System.out.println(OrderYear);
    	System.out.println("------------------------------------");
    	System.out.println("Item Type  Qty Unit/Price Sub-Total");
    	System.out.println("------------------------------------");
    	System.out.print("Shirts      " + numberOfShirts + "     ");
    	System.out.println(priceOneShirt + "     " + subTotalShirts);
    	System.out.print("Pants       " + numberOfPants + "     ");
    	System.out.println(priceAPairOfPants + "     " + subTotalPants);
    	System.out.print("Dresses     " + numberOfDresses + "     ");
    	System.out.println(priceOneDress + "     " + subTotalDresses);
    	System.out.println("------------------------------------");
    	System.out.println("Number of Items: " + totalNumberOfItems);
    	System.out.println("Total Order:     " + totalOrder);
    	System.out.print("Tax Rate:        " + salesTaxRate * 100);
    	System.out.println('%');
    	System.out.println("Tax Amount:      " + taxAmount);
    	System.out.println("Net Price:       " + netPrice);
    	System.out.println("====================================");
        }
    }
  2. Execute the application and perform a cleaning order. Here is an example of running the program:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts         5     0.95     4.75
    Pants         2     2.95     5.9
    Dresses     3     4.55     13.649999999999999
    ------------------------------------
    Number of Items: 10
    Total Order:     24.299999999999997
    Tax Rate:        5.75%
    Tax Amount:      0.013972499999999999
    Net Price:       24.286027499999996
    ====================================
 

Previous Copyright © 2005 FunctionX, Inc. Next