Input/Output: Basic Input Using Scanner Class
Input/Output: Basic Input Using Scanner Class
INPUT/OUTPUT
Java effectively handles input and output operations.
For input operations, you are already familiar that BufferedReader class is used, but
input operations are handled by Java using
Scanner class.
When working with documents you will often require printing them to a selected printer.
A helpful addition is the ability to visually
look on paper through a print
preview and to choose options which define the behavior of how the document is
printed.
preview how the document
Let us study the concept of Input/Output and other related things in terms of Java
Programming.
BASIC INPUT USING SCANNER CLASS
The numeric values may all be on one line with blanks between each value or
be on separate lines. Whitespace characters (blanks or carriage returns) acr separators. The next method
returns the next input value as a string, regardless ^
what has been typed. For example, given the following code segment and data. ° int number = in.nextlnt
f
( );
float real = ln.nextFloat( );
long number2 = (n.nextLong ( ); double real2 = in.nextDouble( );
String string = in.next( ); 66 28
22222222222 32222.33 End.
66 would be stored in number, 28.0 would be stored in reat, 22222222222 would be stored in number?,
32222.33 would be stored in real?, and End would be stored in
string.
The method nextFloat( ) reads an integer and stores it as a float value. This is acceptable because an
integer value can be stored exactly as a real value; there is
no ambiguity. If we had entered a decimal point after the 66 the system would have thrown an
InputMismatchException regardless of whether or not a non-zero value
followed the decimal point. An arbitrary real number cannot be stored exactly as an integer; it is
ambiguous. Remember that anything ambiguous is illegal.
nextLine( ) reads the rest of the line and returns it as a string. The carriage return is consumed but is not
appended to string. The numeric reads do not consume the
whitespace, so if a nextLine is issued at after a numeric read and the numeric value is at the end of the
line, nextLine returns the empty string.
ILLUSTRATION:
}
}
Output of the Program
Enter integer number, double type number, Word Line
25
TD Malhotra
25:76.98:TD: Malhotra
ILLUSTRATION:-
Use of Scanner class for different inputs.
import java.util.Scanner;
import java.io.*;
public class Scan {
public void scanning() {
Scanner in = new Scanner(System.in);
int integer;
long longlnteger;
float realNumber;
String stringl;
String string2;
System.out.println ("Enter an integer");
integer = in.nextlnt( );
System.out.println("Enter a Long integer");
longlnteger = in.nextLong();
System.out.println("Enter a Float Number");
realNumber = in.nextFloat();
stem.out.println("Enter a string.");
stringl = in.nextLine();
System.out.println("Now enter another value.");
string2 = in.next();
System.out.println("You have entered: ");
SYStem.outprintin(integer +"" + longlnteger +"»+ dumber +stringl + " and " + string2);
Sys
}
•
•
}
Output of the Program
ENTE an integer
12
Enter a Long integer 1222234
Enter a Float Number 442949.22
Enter a string.
Now enter another value,
Vikas Malhotra
You have entered:
12 1222234 442949.22
and Vikas Malhotra
PRINTING IN JAVA
•
The system controls the overall printing process, just like it controls when and how a program can
draw. Your application provides information about the document to be
printed and the printing system determines when each page needs to be rendered. This callback
printing model enables printing to be supported on a wide range of
printer and systems. It even allows users to print to a bitmap printer from a computer that doesn't
have enough memory or disk space to hold the bitmap of an
entire page. In this situation the printing system will ask your application to render the page
repeatedly so that it can be printed as a series of smaller images. (These
smaller images are typically referred to as bands and this process is commonly called banded
printing.)
Java Printing API
The Java Printing API is based on a callback printing model in which the printing system, not the
application, controls when pages are printed. The application provides information about the
document to be printed and the printing system asks the
application to render each page as it needs them.
The printing system might request that a particular page be rendered more than once or request that
pages be rendered out of order. The application must be able
to generate the proper page image, no matter which page the printing system requests. In this
respect, the printing system is similar to the window toolkit, which
can request components to repaint at any time, in any order.
The callback printing model is more flexible than traditional application-driven printing models and
supports printing on a wider range of systems and printers. For example,
if a printer stacks output pages in reverse order, the printing system can ask the application to
generate pages in reverse order so that the final stack is in proper
reading order.
This model also enables applications to print to a bitmap printer from computers that don't have
enough memory or disk space to buffer a full-page bitmap. In this
situation, a page is printed as a series of small bitmaps or bands. For example, if
only enough memory to buffer one tenth of a page is available, the page is divided , ten bands. The
nt0
job Control
Although the system controls the overall printing process, your application has to get the ball rolling by
setting up a Printer Job. The Printer Job, the key point of
control for the printing process, stores the print job properties, controls the display of print dialogs and is
used to initiate printing.
To steer the Printer Job through the printing process, your application needs to :
Get a PrinterJob by calling PrinterJob.getPrinterJob
Tell the PrinterJob where the rendering code is by calling set Printable or setPageable
If desired, display the Page Setup and Print dialogs by calling page Dialog and
print Dialog
Initiate printing by calling print
The rendering of pages is controlled by the printing system through calls to the
application's imaging code.
Imaging
Your application must be able to render any page when the printing system requests it This rendering
code is contained in the print method of a page painter-a class
that implements the Printable interface. You implement print to render page contents bv usinq a Graphics
or a Graphics2D rendering context. You can use either one page
to render all of the pages in a print job or different page painters for different types of pages. When the
printing system needs to render a page, it calls
print on the appropriate page painter.
ou use a single page painter, the print job is called a printable job. Using a ble job is the simplest way to
W
painters and Pagef ormat/,. The printing v/'tem can aok the page painters to renter pages In any
order and pages can be skipped* For example, if a user prints pages 2
and 3 of a document, the page painter will be a'>ed to render only the pages at indices 1 and 2.
The multiple page painters in a pageable Job are coordinated by a dass that implements the
Pageable interface, such as Book, A Book represents a collection of
pages that can use different page painters and that can vary in size and orfentatkw. You can also
use your own implementation of the Pageable interface if Book does
not meet your application's needs.
A Pageable job has the following characteristics:
Each page can have its own painter. For e/ample, you could have a painter implemented to print the
cover page, another painter to print the table of
contents and a third to print the entire document
YOU can set a different page format for each page in the boot In a Pageable job, you can mix
portrait and landscape pages.
The print subsystem might ask your application to print pages out of sequence and some pages may
be skipped if necessary. Again, you do not
have to worry about this as long as you can supply any page in your document on demand.s he
Pageable job doesn't need to know how many pages are in the document.
CLASS PRINTERJOB
The PrmterJob class Is the principal class that controls printing. An application calls
thods In this class to set up a job, optionally to invoke a print dialog with the
and then to print the pages of the job.
user
me
Methods
•
Summary
abstract void
cancel()
It cancels a print job that is in progress.
PageFormat
defaultPage()
It creates a new PageFormat instance and sets it to a default size and orientation.
abstract PageFormat
defaultPage(PageFormat page)
It clones the PageFormat argument and alters the clone to describe a default page size and
orientation.
abstract intgetCopies()
It gets the number of copies to be printed.
geUobName(
)
abstract String
It gets the name of the document to be printed.
GetPageFormat (PrintRequestAttributeSet attributes)
Page Format
It calculates a Page Format with values consistent with those supported by the current Print Service
for this job (i.e. the value returned by setPrintService()) and media, printable area and
orientation contained in attributes.
getPrinterJob ()
static Printer Job
It creates and returns a Printer Job which is initially associated with the default printer.
getPrintService ()
Print Service
It returns the service(Printer) for this printer job.
get Username()
Abstract String
It gets the name of the user of printing.
is Cancelled()
abstract Boolean
It returns true if a print job is in progress, but is going to be cancelled at the next opportunity;
otherwise it returns false.
•
LookupPrintServices ()
printService [ ]
Static
A convenient method which looks up 2D print services.
lookup5treamPrintServices (String
StfwmPrlnlScsrvlcor ;iciory[ ] A convenient method which locates factories f
: 0r
mime Type
Stream print services which can image 2D graphics pageDJalog (PageFbrmat page)
It displays a dialog that allows modification of Page Format instance.
a
page Dialog(PrintRequestAttributeSet
A convenient method which displays a cross- platform page setup dialog.
Attributes)
PafjeFormat
prlnt( )
It prints a set of pages. print (PrintRequestAttributeSet attributes)
.ibstract void
Void
It prints a set of pages using the settings in the attribute set.
print Dialog(
It presents a dialog to the user for changing the properties of the print job.
print Dialog(PrintRequestAttributeSet)
abstract boolean
attributes)
boolean
A convenient method which displays a cross- platform print dialog for all services which are
capable of printing 2D graphics using the Page able interface.
SetCopies (int
It sets the number of copies to be printed.
SetJobName (String Copies)
Abstract void
job Name
)
abstract void
It sets the name of the document to be printed.
setPageable (Page able document)
Abstract void
It queries document for the number of pages and the Page Format and Printable for each page held
in the pageable instance, document.
abstract void
set Printable(Printable painter)
It calls painter to render the pages.
abstract void
set Printable(Printable painter, PageFormat format)
It calls painter to render the pages in the specified format.
void
setPrintService (Print Service service)
It associates this Printer Job with a new PrintService.
abstract PageFormat
validate Page(PageFormat page)
It returns the clone of page with its settings adjusted to be compatible with the current
printer
of this Printer Job.
•
g2.draw (rectangle);
Return PAGE_EXISTS;
case 1 : g2.setColor(Color.red);
g2.draw(circle);
return PAGE_EXISTS;
default: return NO_SUCH_PAGE;
}
}
}
public class PrintSample {
public static void main(String argsf ]) throws Exception {
Printer Job pjob = PrinterJob.getPrinterJob ();
pjob.setPrintable (new Print Object( ));
if(pjob.printDialog()) {
try { pjob.print();
}
catch(PrinterException e) {
System.out.println (e); pjob.print ();
}
}
}
You can display either the Print or the Page Setup dialog box. This enables you to create
unattended print jobs, an ability that becomes useful when you want to set a server to print
documents. Using dialogs on a
desktop-type application promotes user-friendliness. Let us take a look at the Print dialog box as
shown in the following picture: