CHAPTER 11

SIMPLE INPUT/OUTPUT

Modern computers have many input/output (i/o) devices. Any modern programming language should provide methods to work with them. Java is no exception. However, at this stage, we will discuss only conventional devices like keyboard and monitor. We will discuss files in a separate chapter. These days most of the programs use GUI. Input/output techniques for these applications will be discussed later.

At this stage, we will concentrate only on console input/output.

11.1 Concepts of Streams, Stream Classes

From the days of C language, input/output is made stream based. The data is supposed to flow as a stream. Languages support methods to work with these streams.

When data flows from input device to computer (CPU to be more precise) it will be called input stream, while when computer sends data to output device it will be called output stream (see Figure 11.1).

Java has excellent organization of classes for handling these streams. There are two ways to classify the streams. The first way is based on the direction of flow, that is input stream and output stream.

Another way of classification is based on the nature of raw data. Basic data type in a computer is byte. Hence, basic streams handle bytes. However, most of the users are familiar only with characters. Hence, streams of another type are required which handle characters.

This makes four main types of streams which are as follows:

  • Byte-oriented input stream
  • Byte-oriented output stream
  • Character-oriented input stream
  • Character-oriented output stream

In the package java.lang, an important class named System is defined. It has objects (fields) in and out defined in it.

The object in belongs to class InputStream. Note that this object is declared as public, static, and final. Please note that we are not supposed to create this object ourselves. This object represents the “standard” input stream. This stream is already open and ready to supply input data. Typically, this stream corresponds to keyboard input or another input source specified by the host environment or user.

The object out belongs to class PrintStream. [Technically better description is that this object is of type/class PrintStream. It belongs to (or part of) class System]. This object is also declared as public, static, and final. It is the standard output stream. This stream is already open and ready to accept output data. Typically, this stream corresponds to display output or another output destination specified by the host environment or user.

Figure 11.1 Input/Output Streams

Figure 11.1 Input/Output Streams

11.2 Character Stream Classes

The most common output device for the past 50 years is the console (monitor). The most common output is of type text. Text is nothing but collections of characters. Similarly, the common input device is keyboard. Most of the keys represent characters. Therefore, when we start the study of input/output, we come across characters (and not bytes). Hence, in this chapter we will concentrate on character-based input/output streams. Java provides many classes for this purpose. Hierarchy of such classes is shown at the end of the chapter.

We will proceed first with output streams and then with input streams. We will introduce useful classes as and when required.

11.3 Writing to the Screen

So far we have used the method System.out.println(). We can straightaway write all standard primitive data type values as well as strings and objects with the help of this method. To use this method, we do not have to import any package. The reason is class System belongs to package java.lang. Since this is the most important package, Java automatically imports it for us (programmers). We can use any class from this package without importing it.

The class System has a field called out. This belongs to class PrintStream.

Let us start with a program to study it formally.

Problem: Write a program to illustrate the use of character-based output stream, for example PrintStream.

Solution: See Program 11.1.

 

PROGRAM 11.1 char1.java

 // char1.java

 import java.io.* ;

 class money

   { int rupee;

   int paise ;

   public money(int a, int b)

     {  rupee =a;paise =b; };

   }

 class char1

 { public static void main(String[] args) throws IOException

      { char k=’A’ ;

        int i = 100 ;

        double pi = 3.14;

        String st1= “GOD”;

        money amt1 = new money(20,30);

        System.out.println(“<---char1.java starts--->”);

        System.out.println(“1) character : “ + k );

        System.out.println(“2) integer   : “ + i );

        System.out.println(“3) double    : “ + pi );

        System.out.println(“4) string    : “ + st1 );

        System.out.println(“5) object    : “ + amt1 );

      }

 } ;

If you run the program, you will get the following output.

 

Output

 <---char1.java starts--->

 1) character : A

 2) integer   : 100

 3) double    : 3.14

 4) string    : GOD

 5) object    : money@3e25a5

Note that when we write object, a string supplied by toString() method of that object is written. Hence, we see a string money@3e25a5. If you want a decent output in its place, you have to write your own version of toString() for that object.

When we write one data element on one line, it is fine. But if we try to write two or more data items on one line, the result is confusing. All elements are written without any space in between. This calls for formatting the output.

11.4 Simple Formatting

So far, we have used a simple trick in println statement. We place either blanks or tab in between two values. Actually, we can do little better than that. Suppose we want that every value is written in a 10-column width. What we can do is as follows. First, get a StringBuffer with 10 blanks. (As strings are immutable, we have to use StringBuffer.) Now we prepare a string of value to be printed and insert it in this buffer. Actually method insert() does it automatically. It has the following form:

insert (position, variable) ;

It inserts the string value of a variable at a given position. In return, it gives us a string which is 10-character wide. Let us use this technique in a program.

Problem: Write a program to demonstrate simple formatting of output.

Solution: Consider a problem of square and cube. Write a program to print a table of square and cubes of first 10 natural numbers (see Program 11.2).

 

PROGRAM 11.2 Simple Formatting I

 //    format1.java

 //    Simple table

 //    formatted output.

 import java.io.* ;

 class format1

 {  public static void main(String[] args) throws IOException

    { int i , sq , cube ;

      System.out.println(“<---format1.java starts--->”);

      System.out.println(“Unformatted output”);

      for(i=1;i< =10;i++)

        {  sq = i * i;

           cube = sq * i;

           System.out.println(i + “ “ + sq + “ “ + cube);

        }

      System.out.println(“Formatted output”);

      for(i=1;i< =10;i++)

        {  sq = i * i;

           cube = sq * i;

           StringBuffer st1 = new StringBuffer(“ “) ;

           st1.insert(0,i);

           st1.insert(10,sq);

           st1.insert(20,cube);

           System.out.println(st1);

        }

    }

 } ;

If you run the program, you will get the following output.

 

Output

<---format1.java starts--->
Unformatted output
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Formatted output
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

If you have found this procedure a bit cumbersome, wait till you read the next section. In SDK 5, you are in for a pleasant surprise.

11.5 Formatting with printf

Now Java has introduced a new method printf which works more or less like one in language C. It is more convenient not only for those who know C language, but also for those who have no exposure to it. If you wish to print say two integers i and j, you can write

System.out.printf(“format string”, i, j);

Here format string will tell the computer in what format values of i and j should be printed. Please note the syntax of the statement. The format string is in a pair of quotes. Comma separates the format string and the variables to be printed. A format string may look like as follows:

% 1$ 0 20 0.1 f

The following diagram illustrates the details.

diagram illustrates

Please note the following points with respect to the format specifier string.

The format string will have the following components in that order: format specifier, argument index, flags, width, precision, and converter (Table 11.1). Some of them are optional. Some of them are relevant under certain conditions.

 

Table 11.1 Format Specifier

Table 11.1 Format Specifier

Flags: Result of individual flags is as follows:

+: prints plus sign for positive numbers

−: value printed left justified

0: prints leading zeros

Converters: The converters represent the following data types:

d: specifies decimal number

f: specifies floating-point number

s: specifies string

c: specifies character

With this much introduction, let us study it with a program.

Problem: Write a program to study method printf.

Solution: See Program 11.3.

 

PROGRAM 11.3 Method printf

 //   format1a.java

 class format 1a

 { public static void main(String[] args)

      {  int i,j ;

         System.out.println(“<-- format1a.java--->”);

         i= 234;

         j= 54;

         System.out.printf(“i=%5d,j=%10d”, i, j);

      }

 }

If you run the program, you will get the following output.

Output

 <-- format1a.java--->

 i=  234,j=  54

 xx12345xxx1234567890

The last row is added to verify the number of columns used.

Earlier we have seen program format1.java. Using printf statement, it can be rewritten in simple manner. See Program 11.16 in the end of chapter programs.

When it comes to printing floating-point numbers, we have to specify the precision as well. A specifier 10.3f tells the computer to use minimum 10 columns with 3 digits for precision. “f” indicates a floating-point number. Let us see a simple program.

Problem: Write a program to find square root and cube root of first 10 natural numbers.

Solution: See Program 11.4.

 

PROGRAM 11.4 printf II

 //   format3a.java

 class format3a

 {  public static void main(String[] args)

    { int i;

      double j,k ;

      System.out.println("<---format3a.java--->");

      System.out.println(" Number squareroot cuberoot");

     for (i=1; i<11;i++)

       { j= Math.sqrt(i);

         k= Math.pow(i,1.0/3.0);

         System.out.printf("%10d%10.3f%10.3f ",i, j, k);

       }

    }

 }

If you run the program, you will get the following output.

 

Output

<---format3a.java--->
Number squareroot cuberoot
  1 1.000 1.000
  2 1.414 1.260
  3 1.732 1.442
  4 2.000 1.587
  5 2.236 1.710
  6 2.449 1.817
  7 2.646 1.913
  8 2.828 2.000
  9 3.000 2.080
 10 3.162 2.154

Let us write one more program to test various properties of printf statement.

Problem: Write a program to study formatting with method printf.

Solution: See Program 11.5.

 

PROGRAM 11.5 printf III

 //     format4.java

 class format4

 { public static void main(String[] args)

    { int i=27 ;

      float  x = 5.67f ;

      double y = Math.PI ;

      System.out.println(“<-- format4.java--->”);

      System.out.printf(“1) %d ”, i);

      System.out.printf(“2) %10d ”, i);

      System.out.printf(“3) %+010d ”, i);

      System.out.printf(“4) %+10d ”, i);

      System.out.printf(“5) %+-10d ”, i);

      System.out.printf(“6) %10.5f ”, x);

      System.out.printf(“7) %20.15e ”, y);

    }

  }

If you run the program, you will get the following output.

 

Output

 <-- format4.java--->

 1) 27

 2)   27

 3)   +000000027

 4)   +27

 5) +27

 6)   5.67000

 7) 3.141592653589793e+00

Note:

  1. Plain decimal format nothing extra.
  2. Width of 10 columns specified.
  3. Sign appears as well as leading zeros.
  4. No leading zeros.
  5. Output left justified.
  6. Width and precision in floating-point representation.
  7. Scientific notation

Let us try one more program.

Problem: Write a program to study formatting of strings and character.

Solution: See Program 11.6.

 

PROGRAM 11.6 Formatting Strings and Character

 //     format5.java

 class format5

 { public static void main(String[] args)

    { String str1 = “This is a string” ;

      char x = ‘X’ ;

      System.out.println(“<-- format5.java--->”);

            System.out.printf(“1) %s ”, str1);

            System.out.printf(“2) %10s ”, str1);

            System.out.printf(“3) %20.6s ”, str1);

            System.out.printf(“4) %+10c ”, x);

     }

  }

If you run the program, you will get the following output.

 

Output

 <-- format5.java--->

 1) This is a string

 2) This is a string

 3)             This i

 4)         X

Note:

  1. Simple formatting for string.
  2. When specified width is insufficient, it is ignored.
  3. Setting precision truncates string.
  4. Even characters can be printed with width.

After studying output, let us go for input. Let us investigate how to read effectively.

11.6 Reading the Data

For reading character-oriented data, Java supplies us an abstract class Reader. For actual reading, we may use another non-abstract class derived from it known as InputStreamReader. You can see a simple example read0.java at the end of chapter.

However, for efficiency purpose Java recommends wrapping an InputStreamReader within a BufferedReader.

See the simple program which is mentioned hereafter.

Problem: Write a program to illustrate reading of characters from standard input, that is keyboard.

Solution: See Program 11.7.

 

PROGRAM 11.7 Reading a Character I

 //     read1.java

 import java.io.* ;

 class read1

  { public static void main(String[] args) throws IOException

      {  int i ,k;

         char ch ;

         BufferedReader Jin = new BufferedReader

         (new InputStreamReader (System.in) );

         System.out.println(“program read1.java starts”);

         System.out.print(“ Input a characters and press enter: “);

         ch = (char) Jin.read();

         System.out.println(“from Jin char read is->” + ch );

         System.out.println(“ Character’s integer value is “ + (int) ch);

      }

 } ;

If you run the program, you will see the following output.

 

Output

 program read1.java starts

 Input a characters and press enter: S

 from Jin char read is->S

 Character’s integer value is 83

The program is straight and simple. But please note that to input a character, we have to enter that character and press return key. The keyboard data goes into input stream only when we press the return key.

There is no simple way of getting to know (read) a key without pressing return. Those who know C/C++ will feel the absence of functions to read keys directly.

The first problem is questions like

Do you want to continue? (Y/N)

where it is expected that user only presses a key. If you want this action in Java, you have to type a key and press Return.

There is another misconception. When we say read, we expect to read what has been typed in response to this read instruction. However, when this method is executed there may be some characters already in the input stream (this happens in C/C++ also). The characters present in the stream are accepted. You may write a simple program and verify the fact.

In earlier example, we read a single character. It is possible to read an array of character. The syntax for this is

Jin.read(box,0,100);

The method returns number of characters that are actually read. It reads the characters in a character array named box (first parameter). It reads a maximum of 100 (third parameter) characters. The characters are placed in the array starting from 0th (second parameter) position.

So far, we have read only characters. What about strings? Yes, Java allows us to read strings too. Let us study it now.

11.7 Reading Strings

We have a method readLine( ) for this task (in class BufferedReader). It reads a line of text and returns it as a string. A line means any string (or sequence of characters) terminated by any one of the following:

line feed (‘ ’) character,

carriage return (‘ ’), or

a carriage return followed immediately by a line feed

If the end of the stream has been reached, then it returns null.

Let us see this method in action.

Problem: Write a program to illustrate reading a string from standard input, that is keyboard.

Solution: See Program 11.8.

 

PROGRAM 11.8 Reading String I

 //     io5.java

 import java.io.* ;

 class io5

   { public static void main(String[] args) throws IOException

      {  char k=’B’,l=’P’;

         int i ;

         String st1;

         BufferedReader Jin = new BufferedReader

                   (new InputStreamReader (System.in) );

         System.out.println(“Enter five lines”);

         for(i=0;i<5;i++)

          {  st1= Jin.readLine() ;

             System.out.println(i+ ") " + st1);

          }

       }

   }

If you run the program, you will see the following output.

 

Output

 Enter five lines

 good morning

 0) good morning

 Welcome to java programming

 1) Welcome to java programming

 Viru is man of the series

 2) Viru is man of the series

 Dravid is man of the match

 3) Dravid is man of the match

 India wins test series too!

 4) India wins test series too!

11.8 Reading Data

Reading strings is fine, but one is more interested in reading data. It may be integers, floats, or double. We can read data first as a string, and then extracting individual element is possible.

Consider a case that a string contains a roll number and percentage marks of a student. It goes without saying that the first one is an integer and the second is a floating-point number. When we read this data, it will contain lot of white space characters in between the two data values.

Java provides us a class called StringTokenizer (see Box 11.1 for details). It helps in converting a line of data into what is called as tokens. Token is nothing but a string which does not contain any blanks. Once we have a token (string), we can convert it very easily into individual values.

BOX 11.1 StringTokenizer

Class StringTokenizer accepts a string while creating an object. Assume that the string is

“ I love Java”

The class internally converts it to three tokens (strings) as

“I”, “love”, “Java”

It returns one token at a time when we invoke method nextToken(). We can test if tokens are still available with the help of method hasMoreTokens().

Note that while converting string to tokens, all blanks, tabs, and other separating characters are ignored.

Problem: Write a program to illustrate reading data with the help of StringTokenizer.

Solution: See Program 11.9.

 

PROGRAM 11.9 Reading String II

 //     reading2.java

 //     format free input

 import java.io.* ;

 import java.util.* ;

 class reading2

 {  public static void main(String[] args) throws IOException

     {  int Rollnum ;

        double percent ;

        String st1,substr1="",substr2="";

        BufferedReader Jin = new BufferedReader

                   (new InputStreamReader (System.in) );

        System.out.println("<---reading2.java--->");

        System.out.println("Give data roll no(int) and percentage(double)");

        st1= Jin.readLi ne();

     // System.out.println(st1);

        StringTokenizer st = new StringTokenizer(st1);

        if (st.hasMoreTokens() )

                   substr1 = st.nextToken() ;

              else System.out.println("Error!!! no tokens to get");

        if (st.hasMoreTokens() )

        substr2 = st.nextToken() ;

        else System.out.println("Error!!! no tokens to get");

        System.out.println(" first substring : " + substr1);

        System.out.println("second substring : " + substr2);

        Rollnum = Integer.parseInt(substr1);

        percent = Double.parseDouble(substr2);

        System.out.println("   roll no = " +Rollnum);

        System.out.println("percentage = " +percent);

    }

 } ;

Run the program. While giving data, put any number of blanks and/or tabs in between. A sample output is shown hereafter.

 

Output

 <---reading2.java--->

 Give data roll no(int) and percentage(double)

 22      97.3

  first  substring : 22

 second  substring : 97.3

    roll no = 22

 percentage = 97.3

You will agree that from Java version 5 onwards reading is fairly simple.

So far, we have used a few methods from the class BufferedReader. Table 11.2 describes all the methods from this class.

 

Table 11.2 Methods from Class BufferedReader

Return type Method Description
Void close() Close the stream.
Void mark(int readAheadLimit) Mark the present position in the stream.
Boolean markSupported() Tell whether this stream supports the mark() operation, which it does.
int read() Read a single character.
int read(char[] cbuf, int off, int len) Read characters into a portion of an array.
String readLine() Read a line of text.
Boolean ready() Tell whether this stream is ready to be read.
void reset() Reset the stream to the most recent mark.
long skip(long n) Skip characters.

11.9 Class Scanner

Just as printing is revolutionized in SDK 5 so is the reading. A class named Scanner is defined. Object of this class are useful in breaking down inputs (formatted as well as unformatted) into tokens. These tokens can be easily converted into individual data types. Let us study a program which achieves what is done in Program 11.9 in a much easier way.

Problem: Write a program to read an integer and a double using class Scanner.

Solution: See Program 11.10.

 

PROGRAM 11.10 Class Scanner I

 //   scan1a.java

 import java.io.* ;

 import java.util.* ;

 class scan1a

  {  public static void main(String[] args) throws IOException

      {  int   Rollnum, i ;

         double percent ;

         System.out.println(“<-- scan1a.java--->”);

         System.out.print(“ Input Roll Number and Percentage”);

         Scanner cin = new Scanner(System.in);

         Rollnum= cin.nextInt();

         percent = cin.nextDouble();

         System.out.println("   roll no = " +Rollnum);

         System.out.println("percentage = " +percent);

      }

 }

If you run the program, you will get the following output.

 

Output

 <-- scan1a.java--->

 Input Roll Number and Percentage 22 97.3

   roll no = 22

 percentage = 97.3

Problem: Write another program to find to study class Scanner.

Solution: See Program 11.11.

 

PROGRAM 11.11 Class Scanner II

 //   scanner2.java

 //   copied from scanner1.java

 import java.io.* ;

 import java.util.* ;

 class scanner2

 {

     public static void main(String[] args) throws IOException

        {  int i,j ;

           System.out.println(“<-- scanner2.java--->”);

           System.out.print(“ Input two integers i and j : “);

           Scanner cin = new Scanner(System.in);

           i= cin.nextInt();

           j= cin.nextInt();

           System.out.println(“Integers read are “ + i +” “+ j);

        }

 }

We have executed the program three times to get the following output.

 

Output

 //First Run

 <-- scanner2.java--->

  Input two integers i and j : 23 678

 Integers read are 23 678

 // Second run

 <-- scanner2.java--->

  Input two integers i and j : 2345 67

 Integers read are 2345 67

 // third Run

 <-- scanner2.java--->

  Input two integers i and j : 23 4.5

 Exception in thread “main” java.util.InputMismatchException

        at java.util.Scanner.throwFor(Scanner.java:819)

        at java.util.Scanner.next(Scanner.java:1431)

        at java.util.Scanner.nextInt(Scanner.java:2040)

        at java.util.Scanner.nextInt(Scanner.java:2000)

        at scanner2.main(scanner2.java:13)

In the first run, we gave data in one line. In the second run, we typed first integer, then pressed return, and then gave the second integer. The program ran successfully. In the third run, we gave one integer and one floating-point number. The program failed because of InputMismatchException.

11.10 StreamTokenizer

Earlier we have studied class StringTokenizer. It was tokenizing a single string. The new class StreamTokenizer converts a stream of type reader into tokens.

Following facts can be noted about this class. See the following constructor:

StreamTokenizer (Reader r)

This creates a tokenizer that parses the given character stream.

  1. The most important method is nextToken(). It extracts a token and returns an integer. It also initializes the field “ttype”. The most important thing to note is that it does not return a string representing the token.
  2. Fields nval and sval store the number or the string depending on the token read.
  3. By using suitable methods, the C style or C++ style comments can be ignored.
  4. Method toString() returns a string containing the token and the line number. However, its exact format is not guaranteed.

Let us study this class with the help of a program.

Problem: Write a program to introduce class StreamTokenizer.

Solution: See Program 11.12.

 

PROGRAM 11.12 Streamtokenizer

 //   reading4.java

 //   format free input

 import java.io.* ;

 import java.util.* ;

 class reading4

  { public static void main(String[] args) throws IOException

      {  int Rollnum ;

         double percent ;

         String st1,substr1=””,substr2=””;

         StreamTokenizer tok = new StreamTokenizer

                    (new InputStreamReader (System.in) );

         tok.slashStarComments(true); // ignores C style comments

         System.out.println(“<---reading4.java--->”);

         System.out.println(“Give few lines input”);

         System.out.println(“type CTRL-Z on fresh line to quit”);

         while (tok.nextToken() != StreamTokenizer.TT_EOF) //NUMBER)

           {  System.out.println(“…”+ tok.toString());

              switch (tok.ttype)

              {

                case StreamTokenizer.TT_WORD :

                              System.out.println( tok.sval); break;

                case StreamTokenizer.TT_NUMBER :

                              System.out.println( tok.nval); break;

                default : System.out.println(

                              “Something went wrong”);

              }

           }

      }

 }

If you run the program, you will get the following output.

Output

 <---reading4.java--->

 Give few lines input

 type CTRL-Z on fresh line to quit

 Good morning 23

 …Token[Good], line 1

 --->Good

 …Token[morning], line 1

 --->morning

 …Token[n=23.0], line 1

 --->23.0

 // C++ style comment

 /* C style comment */ ignored

 …Token[ignored], line 3

 --->ignored

Please note that C++ style comment is on line number 2. This has been ignored. However, the next line is properly taken as line number 3.

11.11 Hierarchies of Character-Based i/o Classes

In our programs, we mainly used BufferedReader and InputStreamReader classes. Package java.io provides all the needed APIs for input/output. For character streams, Java provides two abstract super-classes Reader and Writer. They provide support for reading and writing 16-bit characters. Package contains non-abstract subclasses derived from the above classes. Figures 11.2 and 11.3 show the hierarchy of these classes.

Figure 11.2 Character-Oriented Input Stream

Figure 11.2 Character-Oriented Input Stream

Figure 11.3 Output Stream

Figure 11.3 Output Stream

11.12 Hierarchies of Byte-Oriented i/o Classes

Though we use characters for input/output, most of the data in the computer is stored in 8-bit bytes. When we hear music or see a picture, the basic data is in terms of bytes. When we store data to files, again bytes are in action. Java has organized various classes nicely to handle byte streams. The most fundamental classes are InputStream and OutputStream. All other classes descend from them. Figures 11.4 and 11.5 show the hierarchy of these classes.

Figure 11.4 Byte-Oriented Input Stream

Figure 11.4 Byte-Oriented Input Stream

Figure 11.5 Byte-Oriented Output Stream

Figure 11.5 Byte-Oriented Output Stream

We will come across some of these classes later on in the chapter on files.

11.13 End of Chapter Programs

11.13.1 Using class InputStreamReader

Problem: Write a program to use basic class InputStreamReader.

Solution: See Program 11.13.

 

PROGRAM 11.13 Using InputStreamReader

 //    read 0.java

 //    copied from conio2c.java

 import java.io.* ;

 class read0

  { public static void main(String[] args) throws IOException

     { int i ;

       char ch ;

       InputStreamReader Jin =

                    new InputStreamReader(System.in) ;

       System.out.println(“program read0.java starts”);

       System.out.print(“ Input a characters and press enter: “);

       for (i=0; i <7;i++)

         { ch = (char) Jin.read();

           System.out.println(“from Jin char read is->” + ch + “<-”);

           System.out.println(“ Its int value-> “ + (int) ch);

         }

         Jin.close();

     }

  } ;

If you run the program, you will see the following output.

Output

 program read0.java starts

  Input a characters and press enter: AB

 from Jin char read is->A<-

  Its int value-> 65

 from Jin char read is->B<-

  Its int value-> 66

 <-om Jin char read is->

  Its int value-> 13

 from Jin char read is->

 <-

  Its int value-> 10

 CDE

 from Jin char read is->C<-

  Its int value-> 67

 from Jin char read is->D<-

  Its int value-> 68

 from Jin char read is->E<-

  Its int value-> 69

11.13.2 Reading integer

Problem: Write a program to develop method getint() which reads integer value from the keyboard.

Solution: Initially the value typed at the keyboard is read as a string. Then the string is converted into an integer (see Program 11.14).

 

PROGRAM 11.14 Developing getint()

 //   conio1.java

 //   copied from io8.java

 import java.io.* ;

 class conio1

   {

     public static void main(String[] args) throws IOException

       {  int i ;

          System.out.println(“program conio1.java starts”);

          System.out.print(“ Input an integer : “);

          i = getint();

          System.out.println(“Integer read is “ + i );

       }

     static int getint() throws IOException

       {  String st1;

          BufferedReader Jin = new BufferedReader

                     (new InputStreamReader (System.in) );

          st1= Jin.readLine();

          Integer temp = new Integer (st1);

          return temp.intValue();

       } ;

   } ;

If you run the program, you will see the following output.

 

Output

 program conio1.java starts

   Input an integer : 2004

 Integer read is 2004

Please note that this program works correctly only when you type an integer value. Leading or trailing blanks are not allowed. They lead to errors. We can improve this program by using the method trim() from class String. We can write similar programs to read other primitive data types.

11.13.3 Reading into a character array

Problem: Write a program to use a character array to store characters read from the keyboard.

Solution: See Program 11.15.

 

PROGRAM 11.15 Reading a Character II

 //   read2.java

 //   copied from read1.java

 import java.io.* ;

 class read2

   {

     public static void main(String[] args) throws IOException

       {  int i ,k;

          char ch ;

          char box[] = new char[100];

          BufferedReader Jin = new BufferedReader

                     (new InputStreamReader (System.in) );

          System.out.println(“program read2.java starts”);

          System.out.print(“ type few characters and press enter: “);

          k=Jin.read(box,0,100);

          System.out.println(“ number of characters read :” +k);

          for(i=0;i <k;i++)

            System.out.println( i+ “ ) character is “ + box[i]);

        }

   } ;

If you run the program, you will see the following output.

 

Output

 program read2.java starts

   type few characters and press enter: ABCD

   number of characters read :6

 0 ) character is A

 1 ) character is B

 2 ) character is C

 3 ) character is D

 4 ) character is

 5 ) character is

Why is the output showing six characters when only four characters have been typed? The reason is that the carriage return and line feed characters are also read. You can verify the fact by printing the numeric value of those characters.

11.13.4 Formatted output

We have solved the square–cube problem earlier. Let us apply formatting with method printf() to the same problem.

Problem: Write a program to find square and cube of first 10 natural numbers. The output should be well formatted.

Solution: The values of square and cube more digits than the basic number. Hence, different width will be in order. We will also use notation of ‘$’ here (see Program 11.16).

 

PROGRAM 11.16 Formatted Output

 //   format2.java

 class format2

 {  public static void main(String[] args)

      {  int i,j,k ;

         System.out.println(“<-- format2.java--->”);

         for (i=1; i <11;i++)-

           { j= i*i;

             k= j*i;

             System.out.printf(“%1$4d%2$6d%3$8d ”, i, j, k);

           }

       }

 }

If you run the above program, you will get the following output.

 

Output

 <-- format2.java--->

 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

Notice the width of four, six and, eight columns, respectively.

Table 11.3 illustrates constructors for class StringTokenizer.

 

Table 11.3 Constructor Summary: StringTokenizer

StringTokenizer(String str) Constructs a string tokenizer for the specified string
StringTokenizer(String str, String delim) Constructs a string tokenizer for the specified string
StringTokenizer(String str, String delim, boolean returnDelims) Constructs a string tokenizer for the specified string

Table 11.4 illustrates methods from class StringTokenizer.

 

Table 11.4 Method Summary: StringTokenizer

int countTokens() Calculates the number of times that this tokenizer’s nextToken method can be called before it generates an exception
Boolean hasMoreElements() Returns the same value as the hasMoreTokens method
Boolean hasMoreTokens() Tests if there are more tokens available from this tokenizer’s string
Object nextElement() Returns the same value as the nextToken method, except that its declared return value is object rather than string
String nextToken() Returns the next token from this string tokenizer
String nextToken (String delim) Returns the next token in this string tokenizer’s string

Table 11.5 illustrates constructors for class Scanner.

 

Table 11.5 Constructor Summary: Class Scanner

Scanner(File source) Constructs a new Scanner that produces values scanned from the specified file
Scanner(File source, String charsetName) Constructs a new Scanner that produces values scanned from the specified file
Scanner(InputStream source) Constructs a new Scanner that produces values scanned from the specified input stream
Scanner(InputStream source, String charsetName) Constructs a new Scanner that produces values scanned from the specified
input stream
Scanner(Readable source) Constructs a new Scanner that produces values scanned from the specified source
.Scanner(ReadableByteChannel source) Constructs a new Scanner that produces values scanned from the specified channel
Scanner(ReadableByteChannel source, Constructs a new Scanner that produces
String charsetName) values scanned from the specified channel
Scanner(String source) Constructs a new Scanner that produces values scanned from the specified string

Table 11.6 illustrates methods from class Scanner.

 

Table 11.6 Method Summary: Class Scanner

void close() Closes this scanner
Pattern delimiter() Returns the Pattern this Scanner is currently using to match delimiters
String findInLine(Pattern pattern) Attempts to find the next occurrence of the specified pattern ignoring delimiters
String findInLine(String pattern) Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters
String findWithinHorizon (Pattern pattern, int horizon) Attempts to find the next occurrence of the specified pattern
String findWithinHorizon (String pattern, int horizon) Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters
boolean hasNext() Returns true if this scanner has another token in its input
boolean hasNext(Pattern pattern) Returns true if the next complete token matches the specified pattern
boolean hasNext(String pattern) Returns true if the next token matches the pattern constructed from the specified string
boolean hasNextBigDecimal() Returns true if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextBigDecimal() method
boolean hasNextBigInteger() Returns true if the next token in this scanner’s input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method
boolean hasNextBigInteger(int radix) Returns true if the next token in this scanner’s input can be interpreted as a BigInteger in the specified radix using the nextBigInteger() method
boolean hasNextBoolean() Returns true if the next token in this scanner’s input can be interpreted as a boolean value using a case insensitive pattern created from the string true false
boolean hasNextByte() Returns true if the next token in this scanner’s input can be interpreted as a byte value in the default radix using the nextByte() method
boolean hasNextByte(int radix) Returns true if the next token in this scanner’s input can be interpreted as a byte value in the specified radix using the nextByte() method
boolean hasNextDouble() Returns true if the next token in this scanner’s input can be interpreted as a double value using the nextDouble() method
boolean hasNextFloat() Returns true if the next token in this scanner’s input can be interpreted as a float value using the nextFloat() method
boolean hasNextInt() Returns true if the next token in this scanner’s input can be interpreted as an int value in the default radix using the nextInt() method
boolean hasNextInt(int radix) Returns true if the next token in this scanner’s input can be interpreted as an int value in the specified radix using the nextInt() method
boolean hasNextLine() Returns true if there is another line in the input of this scanner
boolean hasNextLong() Returns true if the next token in this scanner’s input can be interpreted as a long value in the default radix using the nextLong() method
boolean hasNextLong(int radix) Returns true if the next token in this scanner’s input can be interpreted as a long value in the specified radix using the nextLong() method
boolean hasNextShort() Returns true if the next token in this scanner’s input can be interpreted as a short value in the default radix using the nextShort() method
boolean hasNextShort(int radix) Returns true if the next token in this scanner’s input can be interpreted as a short value in the specified radix using the nextShort() method
IOException ioException() Returns the IOException last thrown by this Scanner’s underlying Readable
Locale locale() Returns this scanner’s locale
MatchResult match() Returns the match result of the last scanning operation performed by this scanner
String next() Finds and returns the next complete token from this scanner
String next(Pattern pattern) Returns the next token if it matches the specified pattern
String next(String pattern) Returns the next token if it matches the pattern constructed from the specified string
BigDecimal nextBigDecimal() Scans the next token of the input as a BigDecimal
BigInteger nextBigInteger() Scans the next token of the input as a BigInteger
BigInteger nextBigInteger(int radix) Scans the next token of the input as a BigInteger
boolean nextBoolean() Scans the next token of the input into a boolean value and returns that value
byte nextByte() Scans the next token of the input as a byte
byte nextByte(int radix) Scans the next token of the input as a byte
double nextDouble() Scans the next token of the input as a double
float nextFloat() Scans the next token of the input as a float
int nextInt() Scans the next token of the input as an int
int nextInt(int radix) Scans the next token of the input as an int
String nextLine() Advances this scanner past the current line and returns the input that was skipped
long nextLong() Scans the next token of the input as a long
long nextLong(int radix) Scans the next token of the input as a long
short nextShort() Scans the next token of the input as a short
short nextShort(int radix) Scans the next token of the input as a short
int radix() Returns this scanner’s default radix
void remove() The remove operation is not supported by this implementation of Iterator
Scanner skip(Pattern pattern) Skips input that matches the specified pattern, ignoring delimiters
Scanner skip(String pattern) Skips input that matches a pattern constructed from the specified string
String toString() Returns the string representation of this Scanner
Scanner useDelimiter(Pattern pattern) Sets this scanner’s delimiting pattern to the specified pattern
Scanner useDelimiter(String pattern) Sets this scanner’s delimiting pattern to a pattern constructed from the specified string
Scanner useLocale(Locale locale) Sets this scanner’s locale to the specified locale
Scanner useRadix(int radix) Sets this scanner’s default radix to the specified radix

RuleBook

import Java by default imports package java.lang. We do not have to import it specifically.
in, out, err In, out, and err are predefined stream variables.
Writer Abstract class Writer is the super class of all classes used for writing characters.
InputStream Abstract class InputStream is the super class of all classes used for reading bytes.
Reader Abstract class Reader is the super class of all classes used for reading characters.
in The object in belongs to class InputStream. It is standard input stream.
out The object out belongs to class printStream. It is standard output stream.

C++ Corner

Redirection operators << and >> are not supported in Java. If someone likes these operators, for him i/o in C++ is more convenient.

Early versions of Java made reading and writing a bit tough. With the advent of version 1.5, i/o in Java has improved a lot. To some extent, it has become similar to i/o in “C”.

Keywords

BufferedReader, format string, hasMoreTokens(), Hierarchies of character-based i/o classes, in, InputMismatchException, InputStreamReader, nextToken(), Out, printf(), PrintStream, readLine( ), readLine(), Scanner, StreamTokenizer, StringTokenizer, System class

Review Questions

  1. Object System.out belongs to which class?
  2. Which are the simplest formatting techniques when we are using method print()?
  3. Which classes are involved in reading from System.in?
  4. What is the advantage of class StringTokenizer for reading data?
  5. How does class scanner helps in reading data?
  6. Describe various elements of format string in method printf().

Exercises

  1. Write a program to print a 3 × 3 matrix. Assume elements are of type Double.
  2. Write a program to print salary records of a company.
  3. Write an application that inputs a line of text, tokenizes the line with an object of class StringTokenizer, and outputs the tokens in reverse order.
  4. In the following program, we want to print square and cubes of 10 natural numbers. Design suitable format string, so that the output will appear neat and correct. Do not modify any other sentence.

      * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

      //   format6.java

      class format6

      {  public static void main(String[] args)

          {  int i,j,k ;

             System.out.println("<---format6.java--->");

             System.out.println(" num square cube");

             for (i=1; i<11;i++)

               {j= i*i;

                k= j*i;

                System.out.printf(“find suitable format string”, k,j ,i );

               }

           }

        }

      * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.168.211