0% found this document useful (0 votes)
59 views10 pages

Input/Output: Basic Input Using Scanner Class

The document discusses input and output in Java, including the Scanner class for input and printing documents. It provides two examples of using the Scanner class to take different types of input. It then discusses the Java Printing API and printing process, noting that printing is controlled by a callback model where the printing system requests pages from the application. It outlines the key steps in job control and imaging for printing, including setting up a PrinterJob, implementing the Printable or Pageable interface, and rendering pages when requested.

Uploaded by

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

Input/Output: Basic Input Using Scanner Class

The document discusses input and output in Java, including the Scanner class for input and printing documents. It provides two examples of using the Scanner class to take different types of input. It then discusses the Java Printing API and printing process, noting that printing is controlled by a callback model where the printing system requests pages from the application. It outlines the key steps in job control and imaging for printing, including setting up a PrinterJob, implementing the Printable or Pageable interface, and rendering pages when requested.

Uploaded by

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

Chapter 14

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:

Using Scanner class for input


import java.util. Scanner;
public class Scanl {
public void scanning( ) {
Scanner input = new Scanner(System.in);
int n;
double d;
String word;
String line;
System.out.printf'Enter integer number, double type number, Word, Line");
n = input.nextlnt();
d = input.nextDouble();
WORD=INPUT.NEXT(); // returns a String up to next whitespace
line = input.nextLine();

// returns rest of line & vanishes the '\n'
System.out.println(+n +":"+ d + :”d + r + line);
B

}
}
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

printing system asks the application to render each page ten


times, once to fill each band. The application does not need to be aware of the number size of the
or

bands; it simply must be able to render each page when requested.


The Printing Sequence
To support printing, an application needs to perform two tasks:
job control—managing the print job
imaging—rendering the pages to be printed
-

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

support printing. More complex printing operations


ht Use multiple page painters are referred to as pageable jobs. In a pageable job ^instance of a class that
implements the Pageable interface is used to manage the
page painters.
RENDERING MODELS
There are two printing models in Java : Printable jobs and Pageable jobs.
STATIC Lookup streamprintservices (string mine type)
Streamprintservicefactory[] A convenient method which locates factories for
Abstract pageformat stream print service which can image 2d graphics.
Page format Pagedialog (pageformat page)
Abstract void It display a dialog that allows modification of a it
Void display instance
Abdtract Boolean Pagedialog (printrequest attributeset attributes)
Boolean A convenient method which display a cross
Abstract void platform page setup dialog.
Abstract void Print()
Abstract vooid In prints a set of pages.
Abstract vooid Print(printrequestattributeset attributes)
Void IN PRINTS A SET OF PAGES USING THE SETTING IN
Abstract pageformat THE ATTRIBUTset
Printdialog()
It presents a dialog to th user for changing the
properties of the print job.
Printdialog(printrequest attributeset attributes)
A convenient method which display a cross
platform print 2d graphics using the pageable
interface.
Setcopies (int copies)
It sets the number of copies to be printed.
Setjobname (string jobname)
It quires document for the number of pages and
the pageformat and printable for each page held in
the patellae instance, document.
Set print label(print label painter)
It claas painter to render the pages.
Setparintlabel (print label printer,pageformat
format )
It calls painter to render the pages.
Setprinter to render thepages in the specified
format.
Setprintservices this printjob with a new print
service.
Validatepage(pageformat )
Ti calls painter to render the pages in the specified
format.
Setprintservice (printservie service)
It associates this printerjob with a new
printsservice
Validatepage(pageformat page)
It return the cole oof page with its settings
adjusted to be compatable with the current
printeeeeeer oof this printer job.

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.

Setting the Orientation of a Printed Page.


Import java.awt.*;
Import Java.awt print*;
Import java.awtgeom.*;
class PrlntObject implements Printable {
public int prlnt(Graphics gr, Page Format pf, int pagelndex) {
Graphics2D g2 = (Graphics2D) gr;
Rectangle2D rectangle = new Rectangle2D.Double (pf.getImageableX (),
pf.getImageableY(), pf.getImageableWidth(), pf.getImageableHeight());
Ellipse2D circle = new Ellipse2D.Double (100,100,100,100);
switch (pagelndex) {
Case 0: g2.setColor (Color. blue);
*

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 ();
}
}
}

USE PRINT AND PAGE SETUP DIALOG BOXES


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:

Print Dialog Box


With the Print dialog box, the user can select a printer and modify its configuration. The user can
also set the number of copies to print and select the page range. Using this dialog box, you can
transfer control of the
print job to the user. This dialog box provides the only place where the user can decide to proceed
with the print job or cancel it.
Below, you will find a small code excerpt that displays the print dialog box:
if (printJob.printDialog( )) {
try{
printJob.print( );
}
catch (Exception Print Exception) {
PrintException.printStackTrace ( );
}
}
The print Dialog( ) method, part of the PrinterJob class, shows the Print dialog box to the
user. This method returns a Boolean value. If the user selects the Print button, printDialog( )
will return true; if the user selects
the cancel button, the method returns a false value and the print job will not proceed. print
Dialog( ) only interacts with your application by returning the Boolean. None of the
parameters set in this dialog box will
affect any of Printer Job’s objects.
The second dialog box is the page setup dialog box. With this dialog box, the user can change the page
setup. The next picture illustrates an example of a Page Setup dialog box :

Page Setup Dialog Box


Using this dialog box, the user can choose all the parameters of the PageFormat object, including the
paper size, the paper source, the orientation of the page and the margins.
The code excerpt beiow shows how to invoke the Page Setup dialog box:
Page Format documentPageFormat = new Page Format ();
DocumentPageFormat = printJob.pageDialog (documentPageFormat);
Book. Append (new Document (), documentPageFormat);
If the user selects the OK button, the page Dialog ( ) method will return a done of the Page Format object
reflecting the user's setup. If the user selects the Cancel button, then the method returns an unaltered
copy
of Page Format.
• Scanner class can parse text for primitive data types.
Objects
• Scanner class can handle different types of data like files, InputSt
§ Scanner is a member of the java.util package.
•d Scanner class is used to obtain input.
• Printable and Page able are the two ways of printing in Java.
• A scanner looks for tokens in input.
• A token is a series of characters that ends with white space.
• A blank, a carriage return or a tab character all are white spaces.
• End of the file is also a whitespace.
• next Line() reads the rest of line and returns as a string.
• Carriage return is consumed and not appended to the string.
9Printing is controlled by Printer Job Class.
• Page Format class describes the size and orientation of a page to be pentad’s

You might also like