Professional Documents
Culture Documents
Object-Oriented Program
Logic and Design
Chapter 9: Getting
Program Input
SY 2019-2020 | SECOND SEMESTER | FOR MARCH 16 – 31, 2020
Getting Program Input
• Programs get data or inputs from external
sources: from users or from files. Often,
programs interact with users by getting input
from the keyboard.
• Another way to pass data to programs is
through the command line when the java
command is issued.
• This chapter explains getting input from these
sources:
❑ From the command line
❑ From the keyboard
Command Line Arguments
• A java application can accept any number of
arguments from the command line.
• Command-line arguments allow the user to
affect the operation of a program when it is
invoked.
• The user enters arguments when invoking
the program by specifying them after the
name of the class to be run.
Command Line Arguments
• For example, a java application program
called “AverageGrade” takes in three
numbers and prints out the average grade.
• To run this program you enter the following
on the MSDos command line (for Windows)
or in the unix command line:
• Java AverageGrade 90 60 80
• Note: The arguments are separated by
spaces
Command Line Arguments
• The inputs supplied with the java command are passed
as an argument to the main method of the class.
If (args.length != 5) { System.out.println(“Invalid
number of arguments”);
System.out.println(“Please enter 5 arguments”);
}
else {
// some statements here
}
Command Line Arguments in NetBeans
• • To pass command-line arguments in NetBeans:
• 1. In the main menu, click on “Run” then select “Set Project
Configuration”. In the sub-menu, select “Customize”.
Command Line Arguments in NetBeans
• Passing Command-Line Arguments in NetBeans
2. Enter the data to be passed to the program in the input box
labeled “Arguments”. Click the “OK” button at the bottom.
3. Run the program.
Getting Input Using BufferedReader
• User inputs can be passed to a program by using
java’s Reader classes. One such class is the
BufferedReader class.
• The BufferedReader class is found in the java.io
package. To use the class and its methods, the
following packages must be imported:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
Getting Input Using BufferedReader
• Program code using BufferedReader:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class GetKeyboardInput {
public static void main (String [] args ) {
BufferedReader dataIn = new BufferedReader (new
InputStreamReader(System.in));
String name = “”;
System.out.print (“Please enter your name: ”);
Getting Input Using BufferedReader
• Program code using BufferedReader – cont’d
try {
name = dataIn.readLine();
} catch (IOException e){
System.out.println(“IO Error”);
}
System.out.println(“Hello ” + name);
}
}
Getting Input Using BufferedReader
• Explanation of Program code:
• The statement
import javax.swing.JOptionPane;