SlideShare a Scribd company logo
1 of 23
MODULE 1:
Object-Oriented Program
Logic and Design
Chapter 9: Getting
Program Input
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.
• The main method
public static void main (String [] args) accepts the
arguments and stores it in an array of String named args.
• The arguments get stored in the args array as:
• args *0+ = “90”
• args *1+ = “60”
• args *2+ = “80”
Command Line Arguments
• Remember that args is an array of Strings,
therefore, numbers passed to the program from
the command-line will be stored as Strings.
• For numbers to be usable, the parseInt method of
the Integer class can be used to convert a String
argument to an integer:
int firstArg = 0;
if (args.length > 0) {
firstArg = Integer.parseInt(args[0]);
}
Command Line Arguments
• Before using command line
arguments, always check the number
of arguments before accessing the
array elements.
• Accessing an element beyond what
was given will generate an exception
or an error.
• Command
Command Line Arguments
• For example, if a program needs 5 inputs from the user,
the following code will check if 5 arguments have been
provided:
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:
• Importing the java.io package is necessary
to be able to use the classes in the package:
BufferedReader and InputStreamReader.
The class IOException handles IO exceptions or
errors that may occur during runtime.
Getting
Getting Input Using BufferedReader
• The statement
BufferedReader dataIn =
new
BufferedReader(newInputStreamReader(System.in));
- declares and creates an object dataIn which
is of type BufferedReader. dataIn is “chained” to
another object of type InputStreamReader, which,
in turn, reads the s tandard input device of
System.in
Getting Input Using BufferedReader
• The statement(s)
try {
name = dataIn.readLine();
} catch (IOException e) {
System.out.println(“IO Error”);
}
- The try and catch blocks are necessary in case IO
errors occur during program execution
Getting Input Using BufferedReader
- In the try block, the statement: name =
dataIn.readLine();
reads a line from the object dataIn (which is connected
to the standard input device, System.in) and stores it in
the String name.
The statement
System.out.println(“Hello ” + name);
prints the String, name.
Getting Input Using JOptionPane
• Another way to get input from the
user is by using the JOptionPane class
which is found in the javax.swing
package.
• JOptionPane makes it easy to pop up
a dialog box that prompts the user for a
value or informs them of something.
Getting
Getting Input Using JOptionPane
• Program code using JOptionPane:
import javax.swing.JOptionPane;
public class PopUpInput {
public static void main (String [] args ) {
String name = “”;
name = JOptionPane.showInputDialog(“Please enter
your name: ”); String msg = “Hello ” + name + “!”;
JOptionPane.showMessageDialog (null, msg);
}
}
Getting Input Using JOptionPane
• Explanation of Program code:
• The statement
import javax.swing.JOptionPane;
is necessary to be able to use the
JOptionPane class and its methods in the
javax.swing package.
Getting Input Using JOptionPane
• In the statement name =
JOptionPane.showInputDialog(“Please enter your name: ”);
• The showInputDialog method of the JOptionPane class
displays a dialog box with a message, a textfield and an OK
button like the one shown below.
Getting
• When the user keys in a value in the
textfield, it is stored in the String variable
name.
• The output message is assembled in the
statement: String msg = “Hello ” + name
+ “!”;
Getting Input Using JOptionPane
Getting Input Using JOptionPane
• The statement, JOptionPane.showMessageDialog
(null, msg);
displays a dialog box containing the message and an
OK button.

More Related Content

What's hot

Unit of competency
Unit of competencyUnit of competency
Unit of competencyloidasacueza
 
Interfaces In Java
Interfaces In JavaInterfaces In Java
Interfaces In Javaparag
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHoang Nguyen
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialscesarmendez78
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2Techglyphs
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 

What's hot (20)

Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
Ppt chapter07
Ppt chapter07Ppt chapter07
Ppt chapter07
 
Java interface
Java interfaceJava interface
Java interface
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
 
Interfaces In Java
Interfaces In JavaInterfaces In Java
Interfaces In Java
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Pptchapter04
Pptchapter04Pptchapter04
Pptchapter04
 
Mpl 1
Mpl 1Mpl 1
Mpl 1
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorials
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java & advanced java
Java & advanced javaJava & advanced java
Java & advanced java
 

Similar to Getting Program Input (20)

Java Notes
Java Notes Java Notes
Java Notes
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
02basics
02basics02basics
02basics
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
 
JAVA_BASICS.ppt
JAVA_BASICS.pptJAVA_BASICS.ppt
JAVA_BASICS.ppt
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Java
JavaJava
Java
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.Net
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
Overloadingmethod
OverloadingmethodOverloadingmethod
Overloadingmethod
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Reading and writting
Reading and writtingReading and writting
Reading and writting
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
Java ppt
Java pptJava ppt
Java ppt
 
C#2
C#2C#2
C#2
 

More from Dr. Rosemarie Sibbaluca-Guirre

More from Dr. Rosemarie Sibbaluca-Guirre (20)

Korean Language: Culture 한국어 개요
Korean Language: Culture 한국어 개요Korean Language: Culture 한국어 개요
Korean Language: Culture 한국어 개요
 
Korean Language Overview 한국어 개요
Korean Language Overview 한국어 개요Korean Language Overview 한국어 개요
Korean Language Overview 한국어 개요
 
Conjunction 접속사
Conjunction   접속사Conjunction   접속사
Conjunction 접속사
 
Pronoun 대명사
Pronoun  대명사Pronoun  대명사
Pronoun 대명사
 
Usage of Particles 입자의 사용
Usage of Particles 입자의 사용Usage of Particles 입자의 사용
Usage of Particles 입자의 사용
 
Usage of Particles 입자의 사용
Usage of Particles 입자의 사용Usage of Particles 입자의 사용
Usage of Particles 입자의 사용
 
Korean Word Order 한국어 단어 순서
Korean Word Order 한국어 단어 순서Korean Word Order 한국어 단어 순서
Korean Word Order 한국어 단어 순서
 
Korean Number 한국 번호
Korean Number 한국 번호Korean Number 한국 번호
Korean Number 한국 번호
 
ISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptx
ISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptxISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptx
ISAD 313-3_ TOOLS OF THE SYSTEM ANALYSIS.pptx
 
ISAD 313-1_INTRODUCTION TO SYSTEMS.pptx
ISAD 313-1_INTRODUCTION TO SYSTEMS.pptxISAD 313-1_INTRODUCTION TO SYSTEMS.pptx
ISAD 313-1_INTRODUCTION TO SYSTEMS.pptx
 
ISAD 313-2_ SYSTEM ANALYSIS.pptx
ISAD 313-2_ SYSTEM ANALYSIS.pptxISAD 313-2_ SYSTEM ANALYSIS.pptx
ISAD 313-2_ SYSTEM ANALYSIS.pptx
 
ISAD 313-4_ RESEARCH PROJECT.pptx
ISAD 313-4_ RESEARCH PROJECT.pptxISAD 313-4_ RESEARCH PROJECT.pptx
ISAD 313-4_ RESEARCH PROJECT.pptx
 
ISAD 313-3_ SYSTEM FLOW.pptx
ISAD 313-3_ SYSTEM FLOW.pptxISAD 313-3_ SYSTEM FLOW.pptx
ISAD 313-3_ SYSTEM FLOW.pptx
 
ISAD 313-3_ MODELS.pptx
ISAD 313-3_ MODELS.pptxISAD 313-3_ MODELS.pptx
ISAD 313-3_ MODELS.pptx
 
ACCT11_9_Financial Position.pptx
ACCT11_9_Financial Position.pptxACCT11_9_Financial Position.pptx
ACCT11_9_Financial Position.pptx
 
ACCT11_8_Equity.pptx
ACCT11_8_Equity.pptxACCT11_8_Equity.pptx
ACCT11_8_Equity.pptx
 
ACCT11_7_Performance.pptx
ACCT11_7_Performance.pptxACCT11_7_Performance.pptx
ACCT11_7_Performance.pptx
 
ACCT11_6_Worksheet.pptx
ACCT11_6_Worksheet.pptxACCT11_6_Worksheet.pptx
ACCT11_6_Worksheet.pptx
 
ACCT11_5_Adjusting Entries.pptx
ACCT11_5_Adjusting Entries.pptxACCT11_5_Adjusting Entries.pptx
ACCT11_5_Adjusting Entries.pptx
 
ACCT11_4_Trial Balance.pptx
ACCT11_4_Trial Balance.pptxACCT11_4_Trial Balance.pptx
ACCT11_4_Trial Balance.pptx
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

Getting Program Input

  • 1. MODULE 1: Object-Oriented Program Logic and Design Chapter 9: Getting Program Input
  • 2. 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
  • 3. 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.
  • 4. 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
  • 5. Command Line Arguments • The inputs supplied with the java command are passed as an argument to the main method of the class. • The main method public static void main (String [] args) accepts the arguments and stores it in an array of String named args. • The arguments get stored in the args array as: • args *0+ = “90” • args *1+ = “60” • args *2+ = “80”
  • 6. Command Line Arguments • Remember that args is an array of Strings, therefore, numbers passed to the program from the command-line will be stored as Strings. • For numbers to be usable, the parseInt method of the Integer class can be used to convert a String argument to an integer: int firstArg = 0; if (args.length > 0) { firstArg = Integer.parseInt(args[0]); }
  • 7. Command Line Arguments • Before using command line arguments, always check the number of arguments before accessing the array elements. • Accessing an element beyond what was given will generate an exception or an error. • Command
  • 8. Command Line Arguments • For example, if a program needs 5 inputs from the user, the following code will check if 5 arguments have been provided: If (args.length != 5) { System.out.println(“Invalid number of arguments”); System.out.println(“Please enter 5 arguments”); } else { // some statements here }
  • 9. 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”.
  • 10. 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.
  • 11. 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;
  • 12. 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: ”);
  • 13. 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); } }
  • 14. Getting Input Using BufferedReader • Explanation of Program code: • Importing the java.io package is necessary to be able to use the classes in the package: BufferedReader and InputStreamReader. The class IOException handles IO exceptions or errors that may occur during runtime. Getting
  • 15. Getting Input Using BufferedReader • The statement BufferedReader dataIn = new BufferedReader(newInputStreamReader(System.in)); - declares and creates an object dataIn which is of type BufferedReader. dataIn is “chained” to another object of type InputStreamReader, which, in turn, reads the s tandard input device of System.in
  • 16. Getting Input Using BufferedReader • The statement(s) try { name = dataIn.readLine(); } catch (IOException e) { System.out.println(“IO Error”); } - The try and catch blocks are necessary in case IO errors occur during program execution
  • 17. Getting Input Using BufferedReader - In the try block, the statement: name = dataIn.readLine(); reads a line from the object dataIn (which is connected to the standard input device, System.in) and stores it in the String name. The statement System.out.println(“Hello ” + name); prints the String, name.
  • 18. Getting Input Using JOptionPane • Another way to get input from the user is by using the JOptionPane class which is found in the javax.swing package. • JOptionPane makes it easy to pop up a dialog box that prompts the user for a value or informs them of something. Getting
  • 19. Getting Input Using JOptionPane • Program code using JOptionPane: import javax.swing.JOptionPane; public class PopUpInput { public static void main (String [] args ) { String name = “”; name = JOptionPane.showInputDialog(“Please enter your name: ”); String msg = “Hello ” + name + “!”; JOptionPane.showMessageDialog (null, msg); } }
  • 20. Getting Input Using JOptionPane • Explanation of Program code: • The statement import javax.swing.JOptionPane; is necessary to be able to use the JOptionPane class and its methods in the javax.swing package.
  • 21. Getting Input Using JOptionPane • In the statement name = JOptionPane.showInputDialog(“Please enter your name: ”); • The showInputDialog method of the JOptionPane class displays a dialog box with a message, a textfield and an OK button like the one shown below. Getting
  • 22. • When the user keys in a value in the textfield, it is stored in the String variable name. • The output message is assembled in the statement: String msg = “Hello ” + name + “!”; Getting Input Using JOptionPane
  • 23. Getting Input Using JOptionPane • The statement, JOptionPane.showMessageDialog (null, msg); displays a dialog box containing the message and an OK button.