0% found this document useful (0 votes)
14 views

02-2 Input & Output

The document discusses input and output in Java programs using the JOptionPane and Scanner classes. It explains how to create dialog boxes to read and print text, letters, and numbers using JOptionPane. Code examples are provided to demonstrate reading input and displaying output.

Uploaded by

Rebhi Achref
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

02-2 Input & Output

The document discusses input and output in Java programs using the JOptionPane and Scanner classes. It explains how to create dialog boxes to read and print text, letters, and numbers using JOptionPane. Code examples are provided to demonstrate reading input and displaying output.

Uploaded by

Rebhi Achref
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Java Essential Essam Ahmed Abdalla (Abu 3rwa)

Programming Methods 1

Chapter 2

Input & Output

Essam Ahmed Abdalla (Abu 3rwA)


[email protected] - [email protected]

42
Contents

Introduction
JOptionPane Class
▪ Read & Print Text
▪ Read & Print Letter
▪ Read & Print Number
Scanner Class
▪ Read & Print Text
▪ Read & Print Letter
▪ Read & Print Number
BufferedReader Class (You will study later)
Java Essential 43 Essam Ahmed Abdalla (Abu 3rwa)
Introduction
Since its introduction, Java has been notable for its
lack of built-in support for basic input, and for its
reliance on fairly advanced techniques for the
support that it does offer.
The Scanner class was introduced in Java 5.0 to
make it easier to read basic data types from a
character input source.
However, it requires some knowledge of object-
oriented programming to use this class.
The Scanner class is in the package java.util.
Read through Scanner class is non-GUI program.

Java Essential 44 Essam Ahmed Abdalla (Abu 3rwa)


Introduction
Computer users today expect to interact with their
computers using a graphical user interface (GUI).
Java can be used to write GUI programs ranging from
simple applets which run on a Web page to
sophisticated stand-alone applications.
A GUI program offers a much richer type of user interface,
where the user uses a mouse and keyboard to interact
with GUI components such as windows, menus, buttons,
check boxes, text input boxes, scroll bars, and so on.
we show how to read user input with the JOptionPane class in Java.

You're probably more familiar with how to read user


input with the Scanner class.
The JOptionPane class is in the package
javax.swing.JOptionPane.
Java Essential 45 Essam Ahmed Abdalla (Abu 3rwa)
Java Essential Essam Ahmed Abdalla (Abu 3rwa)

(Dialog Box)

46
Custom Dialogs
Dialog boxes are a window in which important
messages addressed to the user are shown, or that
give output from the program.
Many Java applications use dialog boxes to display
text instead of command window such as web
browsers.
Java has several standard dialog boxes that are
defined in the classes JOptionPane, JColorChooser,
and JFileChooser.
The JOptionPane class includes a variety of methods
for making simple dialog boxes that are variations on
three basic types: a “message” dialog, a “confirm”
dialog, and an “input” dialog.

Java Essential 47 Essam Ahmed Abdalla (Abu 3rwa)


Custom Dialogs
The variations allow you to provide a title for the
dialog box, to specify the icon that appears in the
dialog, and to add other components to the dialog box.
The on-line version of this section includes an applet
that demonstrates JOptionPane as well as
JColorChooser.
To show the different dialog boxes, this is done by
javax packages and by using the special methods in
the swing library in the class called (JOptionPane) as
shown in the code below:
import javax.swing.JOptionPane;

Java Essential 48 Essam Ahmed Abdalla (Abu 3rwa)


Java JOptionPane
The JOptionPane class is used to provide standard
dialog boxes such as message dialog box, confirm
dialog box and input dialog box. These dialog boxes are
used to display information or get input from the user.
The JOptionPane class inherits JComponent class.

Java Essential 49 Essam Ahmed Abdalla (Abu 3rwa)


Java JOptionPane
Dialog boxes are divided into three types:
1. Dialog boxes display only a message to the user

JOptionPane.showMessageDialg(null, "Hello Java");

2. Dialog boxes that display a message and receive


values ​from the user
n=JOptionPane.showInputDialog("Enter Number ");

Values ​entered by the user are of type (String).

3. Alert boxes (for example, Error, Question, and


Information)

Java Essential 50 Essam Ahmed Abdalla (Abu 3rwa)


Print Massage
// Printing multiple lines in a dialog box
// Written By: Essam Ahmed Abdalla (Abu 3rwa)
// Java extension packages
import javax.swing.JOptionPane; // import class JOptionPane
public class Prog3
{
// main method begins execution of Java application
public static void main( String args[ ] )
{
JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );

System.exit( 0 ); // terminate application


} // End method main
} // End class Prog3
Java Essential 51 Essam Ahmed Abdalla (Abu 3rwa)
Print Massage

Java Essential 52 Essam Ahmed Abdalla (Abu 3rwa)


System.exit (0(
System.exit(0); // terminate application
The System object is part of the base package
java.lang, which is called implicitly without the need
to import statement.
The System object contains the exit method used to
terminate the application.
This statement must be used in all applications that
use the Graphical User Interface (GUI).
The argument (0) of the method shows that the
application completed successfully terminated and
without error.
And if the entrance is not equal to zero, then that
means there is an error.
Java Essential 53 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Text
// Read the name and Print it in the dialog box
// Written By: Essam Ahmed Abdalla (Abu 3rwa)
// Java extension packages
import javax.swing.JOptionPane; // import class JOptionPane
public class MyName
{
// main method begins execution of Java application
public static void main( String args[ ] )
{
String name=JOptionPane.showInputDialog( "Enter Your Name" );
JOptionPane.showMessageDialog(null, "Welcome"+name );

System.exit( 0 ); // terminate application


} // end method main
} // end class MyName
Java Essential 54 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Text

Java Essential 55 Essam Ahmed Abdalla (Abu 3rwa)


Read & Print Letter
// Read and print a character in the dialog box
// Written By: Essam Ahmed Abdalla (Abu 3rwa)

// Java extension packages


import javax.swing.JOptionPane; // import class JOptionPane
public class ReadChar
{
// main method begins execution of Java application
public static void main( String args[ ] )
{
String st=JOptionPane.showInputDialog( "Enter Letter" );
// Read one character of the text using the charAt(Position) function
char ch=st.charAt(0);
JOptionPane.showMessageDialog(null, “The Letter is "+ch);
System.exit( 0 ); // terminate application
} // End method main
} // End class ReadChar
Java Essential 56 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Letter

Java Essential 57 Essam Ahmed Abdalla (Abu 3rwa)


Read & Print Number
// An addition program.
// Written By: Essam Ahmed Abdalla (Abu 3rwa)

// Java extension packages


import javax.swing.JOptionPane; // import class JOptionPane
public class Addition {

// main method begins execution of Java application


public static void main( String args[ ] )
{
String firstNumber; // first string entered by user
String secondNumber; // second string entered by user
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2

Java Essential 58 Essam Ahmed Abdalla (Abu 3rwa)


Read & Print Number
// read in first number from user as a string
firstNumber =JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a string
secondNumber = JOptionPane.showInputDialog( "Enter second integer" );

// convert numbers from type String to type int


number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// add the numbers
sum = number1 + number2;
// display the results
JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Results",JOptionPane.PLAIN_MESSAGE );

System.exit( 0 ); // terminate application


} // End method main
} // End class Addition
Java Essential 59 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Number

Java Essential 60 Essam Ahmed Abdalla (Abu 3rwa)


JOptionPane.showMessageDialog
JOptionPane.showMessageDialog output sentence
requires four arguments:
The first entry (null): tells the computer to place
the cursor in the center of the screen.
The second entry: The message that will appear in
the dialog box.
The third entry: The text that will appear in the title
line of the dialog box.
The fourth entry: The symbol that shows the type
of dialog box.

JOptionPane.showMessageDialog(null, "The sum is " +


sum, "Results",JOptionPane
Java Essential 61 Essam Ahmed Abdalla (Abu 3rwa)
JOptionPane.showMessageDialog
1. JOptionPane.showMessageDialog(null, "The sum is " + sum);

2. JOptionPane.showMessageDialog(null, "The sum is " + sum,


"Results",JOptionPane.INFORMATION_MESSAGE );
3. JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Results",JOptionPane.PLAIN_MESSAGE );

(1) (2) (3)


Java Essential 62 Essam Ahmed Abdalla (Abu 3rwa)
JOptionPane.showMessageDialog
4. JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Results",JOptionPane.WARNING_MESSAGE);

5. JOptionPane.showMessageDialog(null, "The sum is " + sum,


"Results",JOptionPane.QUESTION_MESSAGE);
6. JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Results",JOptionPane. ERROR_MESSAGE);

(3) (4) (5)


Java Essential 63 Essam Ahmed Abdalla (Abu 3rwa)
‫‪JOptionPane.showMessageDialog‬‬

‫الوصف‬ ‫الرمز‬ ‫نوع رسالة صندوق الحوار‬


‫عرض صندوق حوار مع رسالة للمستخدم‬ ‫ال يوجد رسالة‬

‫عرض صندوق حوار مع رسالة للمستخدم‬ ‫‪JOptionPane.‬‬


‫‪INFORMATION_MESSAGE‬‬

‫يظهر رسالة في الصندوق بدون رموز‬ ‫ال يوجد رمز‬ ‫_‪JOptionPane. PLAIN‬‬
‫‪MESSAGE‬‬

‫عرض صندوق حوار يبين رسالة خطأ‬ ‫_‪JOptionPane. ERROR‬‬


‫للمستخدم‬ ‫‪MESSAGE‬‬

‫رسالة تحذيرية للمستخدم‬ ‫_‪JOptionPane. WARNING‬‬


‫‪MESSAGE‬‬

‫سؤال للمستخدم يجب اإلجابة عليه بنعم أو ال‬ ‫_‪JOptionPane. QUESTION‬‬


‫‪MESSAGE‬‬

‫‪Java Essential‬‬ ‫‪64‬‬ ‫)‪Essam Ahmed Abdalla (Abu 3rwa‬‬


Convert Inputs from type String to Other types
String st =JOptionPane.showInputDialog("Appropriate MSG")

Data Type Convert Method


byte Byte.parseByte(st)
short Short.parseShort(st)
int Int.parseInt(st)
long Long.parseLong(st)
float Float.parseFloat(st)
double Double.parseDouble(st)
boolean Boolean.parseBoolean(st)
char st.charAt(Position)
st.charAt(0)

Java Essential 65 Essam Ahmed Abdalla (Abu 3rwa)


Java Essential Essam Ahmed Abdalla (Abu 3rwa)

(Scanner)

66
Java Scanner
The Scanner class is used to get user input, and
it is found in the java.util package.
The Java Scanner class is widely used to parse
text for strings and primitive types using a
regular expression.
It is the simplest way to get input in Java. By the
help of Scanner in Java, we can get input from
the user in primitive types such as int, long,
double, byte, float, short, etc.

Java Essential 67 Essam Ahmed Abdalla (Abu 3rwa)


Input & Output in Java
The standard computer output unit is the Screen.
The standard computer input unit is the keyboard.
The (System) class was created to handle input
and output units.
The (out) object in the (System) class is used to
handle output.
The (in) object in the (System) class is used to
handle input.

Java Essential 68 Essam Ahmed Abdalla (Abu 3rwa)


Output Statement in Java
The (out) object uses the (print) and (println)
method to print a message on the screen:

System.out.print("Hello Java");

System.out.println("Hello Java");

Java Essential 69 Essam Ahmed Abdalla (Abu 3rwa)


Input Statement in Java
The (in) object in the (System) class is used to
handle input.
The object (System.in) is not used to read in a
simple and direct way, in the same way that the
(System.out) object is used for screen printing.
The (System.in) object reads all entries as Byte values.
The user and some programs need to enter other
types of data such as text, letters and numbers.
This is done by using the object (System.in) in
conjunction with the object derived from the
class (Scanner); where a value is entered and
assigned to a variable.

Java Essential 70 Essam Ahmed Abdalla (Abu 3rwa)


Input Statement in Java
The (Scanner) class is designed to read inputs
from the source such as (System.in) through a
set of ready-made Methods that are used
according to the type of data entered.
The Scanner class is in the package java.util.

Java Essential 71 Essam Ahmed Abdalla (Abu 3rwa)


Steps to create an input sentence in the Java language

1. Invoke Scanner class


import java.util.Scanner;
2. Define a reference variable (object) of the class (Scanner)
Scanner ReferneceVariable;
3. Create an object from the class (Scanner) that connects with
the object (in) in the (System) class, which is the data source.
ReferneceVariable = new Scanner(System.in);
Note :
Steps 2 and 3 can be summarized in one step as follows:
Scanner ReferneceVariable = new Scanner(System.in);
The Reference variable must take into considerate the
conditions for naming the variables; also take into
considerate that the Meaningful label (scan, read, input).

Java Essential 72 Essam Ahmed Abdalla (Abu 3rwa)


Steps to create an input sentence in the Java language

4. Using some special methods in the class


(Scanner) to assign the entered values ​to the
variables according to the type of the variable;
the following table shows an example of this:

Data Type Method Example


int nextInt() int n=input.nextInt();
double nextDouble() double n=input.nextDouble();
String next() String st=input.next();

Java Essential 73 Essam Ahmed Abdalla (Abu 3rwa)


Inputs types using Scanner

Data Type Method Example


byte nextByte() byte n=input.nextByte();
short nextShort() short n=input.nextShort();
int nextInt() int n=input.nextInt();
long nextLong() long n=input.nextLong();
float nextFloat() float n=input.nextFloat();
double nextDouble() double n=input.nextDouble();
boolean input.nextBoolean(); boolean b=input.nextBoolean();
String next() String st=input.next();
char next() String st=input.next();
st.charAt(Position)
st.charAt(0)

Java Essential 74 Essam Ahmed Abdalla (Abu 3rwa)


Read & Print Text
// Read the name and Print it using Scanner
// Written By: Essam Ahmed Abdalla (Abu3rwa)

import java.util.Scanner;
public class MyName2
{
public static void main(String[] args(
{
//2 & 3.(System) ‫( في الفئة‬in) ‫( يتصل بالكائن‬Scanner) ‫تعريف وإنشاء كائن من الفئة‬

Scanner input= new Scanner (System.in);


String name;
System.out.println("Enter Your Name ");
// 4. (Scanner) ‫) الموجودة في الفئة‬next( ‫إستخدام دالة قراءة النص‬

name=input.next(); // name ‫وتخزينه في المتغير‬ ‫إدخال األسم‬


System.out.println( "Welcome "+name);
}
}
Java Essential 75 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Text

(1) (2)

Java Essential 76 Essam Ahmed Abdalla (Abu 3rwa)


Read & Print Letter
// Read a character and print it using Scanner
// Written By: Essam Ahmed Abdalla (Abu 3rwa)

import java.util.Scanner;
public class MyName2
{
public static void main(String[] args(
{
//2 & 3.(System) ‫( في الفئة‬in) ‫( يتصل بالكائن‬Scanner) ‫تعريف وإنشاء كائن من الفئة‬
Scanner input= new Scanner (System.in);
String st; char ch;
System.out.println("Enter Letter ");
// 4. (Scanner) ‫) الموجودة في الفئة‬next( ‫إستخدام دالة قراءة النص‬
st=input.next(); // st ‫إدخال النص وتخزينه في المتغير‬
// Read one character of the text using the charAt(Position) function
ch=st.charAt(0);
System.out.println( "The Letter is "+ch);
}
}
Java Essential 77 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Letter

Java Essential 78 Essam Ahmed Abdalla (Abu 3rwa)


Read & Print Number
// An addition program
// Written By: Essam Ahmed Abdalla (Abu 3rwa)
// 1. Scanner ‫إستدعاءالفئة‬
import java.util.Scanner;
public class Addition2
{
public static void main(String[] args(
{
//2 & 3.(System) ‫( في الفئة‬in) ‫( يتصل بالكائن‬Scanner) ‫تعريف وإنشاء كائن من الفئة‬
Scanner input= new Scanner (System.in);
int n1,n2,sum;
System.out.println("Enter first integer ");
// 4. (Scanner) ‫) الموجودة في الفئة‬nextInt( ‫إستخدام دالة قراءة األرقام الصحيحة‬
n1=input.nextInt(); // n1 ‫إدخال العدد األول وتخزينه في المتغير‬
System.out.println("Enter second integer ");
n2=input.nextInt(); // n2 ‫إدخال العدد الثاني وتخزينه في المتغير‬
sum=n1+n2;
System.out.println( "The Summation="+sum);
}
}
Java Essential 79 Essam Ahmed Abdalla (Abu 3rwa)
Read & Print Number

Java Essential 80 Essam Ahmed Abdalla (Abu 3rwa)


Java Essential Essam Ahmed Abdalla (Abu 3rwa)

(Buffer Reader)

out beyond of this course

81
References
Y. Daniel Liang “Introduction to Java Programming , 8th Edition “ -
Armstrong Atlantic State University,USA – 2012.

Paul & Harvey Deitel “Java™How to Program, 9th Edition” – USA-


2012.

David J. Eck “Introduction to Programming Using Java” – Hobart


and William Smith Colleges - USA – 2006.

Barry Burd “Beginning Programming with Java™ For Dummies®,


3rd Edition” - Published by Wiley Publishing, Inc. – 2005.
http://www.tutorialspoint.com/index.htm
http://www.w3schools.com
http://java.sun.com/docs/books/tutorial/index.html
http://www.javatutorials/tutorial/index.html
http://www.javatpoint.com
Java Essential 82 Essam Ahmed Abdalla (Abu 3rwa)
‫‪Choose your taste‬‬

‫‪Taste #01‬‬ ‫‪Taste #02‬‬ ‫‪Taste #03‬‬

‫الانسان اذلي ميكنه‬ ‫ف‬ ‫ل‬ ‫ا‬


‫الإرادة هي رة ‪ ،‬و‬
‫ك‬ ‫ليست هناك متعة في‬
‫اتقان الصرب ميكنه اتقان‬ ‫الع يرمة هي الروح‬ ‫القتال ‪ ،‬و لكن المتعة‬
‫تكمن في الفوز‬
‫أي شئ أخر‬

You might also like