Download 02-4IO

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CHAPTER 2-4
INTRODUCTION TO I/O
Variable vs object




A data item of a basic type is called a __________.
A data item of a class type is called an _________.
A basic type defines 1 thing: its associated _________________. Thus, a variable possesses a
___________________ only
A class type defines 2 things: its associated ___________________ and ___________________.
Thus, an object possesses a ___________________ and ___________________.
Static methods vs non-static methods




A class definition can define static methods and non-static methods.
Objects only possess ___________________ methods of its class type.
To call the static method m defined by class X, we use the expression X.m(arguments).
To call the non-static method n defined by class X, we use the expression obj.n(arguments), where obj
is an object of class X.
//Example 2-4-1
//Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(4.0));
System.out.println("The square root of 4.0 is "+Math.sqrt(4.0));
}
}
---------------------------------------------------------------------------------------------------------------------------Usage: public static double sqrt(double x)
Return: The square root of x.
---------------------------------------------------------------------------------------------------------------------------Figure 2-4-1. The API of some useful Math methods.
File I/O





A program communicates with its environment. Thus, a program typically reads input data from 1 or
more input devices, processes the data, then produces output onto 1 or more output devices.
Modern operating systems model an I/O device as a data abstraction called a _____ and allow a
program to read from or write to a file instead of interacting directly with an I/O device. This is known
as __________.
The operating system is responsible to transfer information between a file and the corresponding I/O
device, which frees programmers from learning the intrinsic details of physical I/O devices.
Java makes file I/O easy because Java provides numerous file classes for programmers to perform file
I/O
In general, to perform file I/O, a programmer must:
o Decide which file class to use
o
o
Instantiate an object of such a file class
Call upon some non-static methods provided by the object.
Program:
File object of class that models screen:
screen:
To print variable x, program
OS transfers characters from
buffer
invokes a method of file
buffer to screen
object to convert internal
file ptr
representation of x to
characters and
methods
and deposit in buffer
File object of class that models keyboard:
keyboard:
OS transfers characters from
buffer
To read value into variable x, program
keyboard to buffer
invokes a method of file object
file ptr
to convert characters in buffer to
internal representation of x
methods



The file object that models the screen has been pre-defined by Java, and its methods perform
conversion from internal representation of various data types to characters.
The file object that models keyboard has been pre-defined by Java, but its methods do not perform
conversion from characters to internal representation of various data types.
To do keyboard input in Java,
o We must identify a class which
 models the keyboard
 provides methods that perform conversion.
o We must define such an object.
Class PrintStream and the object System.out







Java has pre-defined class PrintStream which models a text file
In addition, Java has pre-created the file object of type PrintStream that corresponds to the screen.
In Computer Science, the file object that corresponds to the screen is known as the
___________________.
In Java, the standard output file object is ___________________.
When a Java program wants to write to the screen, the program simply uses the non-static output
methods provided by ___________________.
To find out what methods System.out provides, we must read the API of its class type, class
PrintStream (see Figure 2-4-1).
Class PrintStream is defined in package java.io.
------------------------------------------------------------------------------------------------------------------Usage: public void print(boolean b)
Output: The characters that represent b ("true" or "false") printed on the screen.
Usage: public void print(char c)
Output: The character c printed on the screen.
Usage: public void print(int i)
Output: The characters that represent i printed on the screen.
Usage: public void print(long n)
Output: The characters that represent n printed on the screen.
Usage: public void print(float f)
Output: The characters that represent f printed on the screen.
Usage: public void print(double d)
Output: The characters that represent d printed on the screen.
Usage: public void print(String s)
Output: The characters in s printed on the screen.
Usage: public void println()
Output: The newline character '\n' printed on the screen.
------------------------------------------------------------------------------------------------------------------Figure 2-4-2. Some useful methods of class PrintStream.


Each of the print methods has a println version that behaves as though it invokes the corresponding
print method followed by a call to println with no argument.
All the print and println methods provided by PrintStream convert binary bytes to characters for human
reading.
//Example 2-4-2
//Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.println(1/3);
System.out.println(22.0/7.0);
System.out.println(22.0F/7.0F);
System.out.println((3>4)&&(5<3));
System.out.println('a');
System.out.println("a");
}
}
//line 7
//line 8
//line 9
//line 10
//line 11
//line 12
The printf method



Class PrintStream has a printf method. Unlike method print or println which takes 1 argument, method
printf is usually called with 2 arguments, namely, a ___________________ followed by an
___________________
The control string contains 2 kinds of elements:
o Conversion specifications. A conversion specification consists of 2 characters, % and a
conversion character. A conversion specification tells printf how to print a value.
 %d specifies a decimal integer format (works for any integral type)
 %f specifies a real number format (works for any floating type)
 %b specifies a boolean format
 %c specifies a character format
 %s specifies a string format.
We must select a proper conversion specification to print the value of an expression.
o Normal characters.
The goal of method printf is to print the control string on the screen. The control string is printed in
the following manner: a normal character is printed as it is, while a conversion specification is replaced
by the value of its corresponding expression in the expression list and printed based on the conversion
character. For example, consider the following printf method call:
System.out.printf("3+5 is %d\n", 8);
Thus, the output is:

Note that the first conversion specification in the control string corresponds to the first expression in
the expression list, the second conversion specification corresponds to the second expression, and so
on. For example, consider the following printf method call:
System.out.printf("3+5 is %d, and 3.2+5.2 is %f\n", 3+5, 3.2+5.2);
The output is:

If there is no conversion specification in the control string, then there is no need for an expression list
to follow. For example, consider the following statements:
System.out.printf ("abc");
System.out.printf ("%s", "abc");
//Example 2-4-3
//Demo.java
public class Demo
{
public static void main(String[] args)
{
int x=2;
double y=4.3;
char ch='a';
String s="hello";
System.out.printf ("x is %d\ny is %f\nch is %c\ns is %s\n", x, y, ch, s);
}
}
 We can specify a field width between the % sign and the conversion character. The value will be
printed right-justified in the field (if the field width is too big) with leading spaces filled with blanks.
If the width specified is too small for the output value, more spaces (just enough) will be allocated to
the field automatically.
o For a decimal integer, we can use %nd where n specifies the field width.
o For a real number, we can use %m.nf where m specifies the entire field width and n specifies the
number of decimal places. If m is omitted, printf will use just enough space to print the real
number, with n decimal digits. The value printed is rounded to n decimal places.
o The field width can be preceded by a – sign for left justification.
//Example 2-4-4
//Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.printf ("%d\n", 5);
System.out.printf ("%4d\n", 5);
System.out.printf ("%f\n", 5.2);
System.out.printf ("%6.2f\n", 5.2);
System.out.printf ("%.2f\n", 5.2);
System.out.printf ("%10s\n", "hello");
System.out.printf ("%-10c", 'x');
System.out.println("done");
}
}
Software engineering principle – output organization
//Example 2-4-5
//Demo.java
public class Demo
{
//Output: The sales tax rounded to 2 decimal digits
public static void main(String[] args)
{
double purchaseAmount = 197.55;
double tax = purchaseAmount * 0.05;
System.out.printf("Sales tax is %.2f\n", tax);
}
}
The object System.in








Java has pre-defined class InputStream which models an input stream of bytes
In addition, Java has pre-created the file object of type InputStream that corresponds to the keyboard.
In Computer Science, the file object that corresponds to the keyboard is known as the
___________________.
In Java, the standard input file object is ___________________.
To find out what methods System.in provides, we read the API of its class type, class InputStream.
Class InputStream is defined in package java.io.
While class PrintStream supports methods such as print, println, and printf which convert binary data
to textual output, class InputStream does not provide methods which convert textual input to binary
data. As a result, when we do console input, we do not directly invoke methods of System.in. Instead,
we use a Scanner object and use methods provided by class Scanner.
Methods of class Scanner convert textual input to binary data.
The Scanner class



Class Scanner is a simple text scanner which accepts its input as a sequence of characters from a
String, a disk file, or the keyboard.
A Scanner breaks its character input into tokens using white space characters as delimiters by default.
The tokens can then be read and converted into values of different basic types using the various "next"
methods provided by class Scanner.
Class Scanner is in package java.util.
------------------------------------------------------------------------------------------------------------------Usage: public int nextInt()
Post:
If next token can be converted to an int, the scanner reads and advances past the token.
Return: If input is successful, the input token read as an int.
Throw: InputMismatchException if next token cannot be translated into a valid int.
NoSuchElementException if there are no more tokens in the Scanner.
Usage:
Post:
Return:
Throw:
public double nextDouble()
If next token can be converted to a double, the scanner reads and advances past the token.
If input is successful, the input token read as a double.
InputMismatchException if next token cannot be translated into a valid double.
NoSuchElementException if there are no more tokens in the Scanner.
Usage: public boolean nextBoolean()
Post:
If next token can be converted to a boolean, the scanner reads and advances past the token.
Return: If input is successful, the input token read as a boolean.
Throw: InputMismatchException if next token cannot be translated into a valid boolean.
NoSuchElementException if there are no more tokens in the Scanner.
Usage:
Post:
Return:
Throw:
public String next()
If next token exists, the scanner reads and advances past the token.
If input is successful, the input token read as a String.
NoSuchElementException if there are no more tokens in the Scanner.
Usage:
Post:
Return:
Throw:
public String nextLine()
If next line exists, the scanner reads and advances past the current line including the newline.
If input is successful, the rest of the current line excluding the newline.
NoSuchElementException if there are no more lines in the Scanner. The last line in the buffer
does not need to end in \n.
----------------------------------------------------------------------------------------------------------------------Figure 2-4-3. Some useful methods of class Scanner.



The "Post" line specifies the ___________________ produced by the method.
The "Return" line specifies the ___________________ produced by the method.
The "Throw" line specifies the ___________________ potentially produced by the method.
Using Scanner to read from a String
//Example 2-4-6
//Demo.java
import java.util.Scanner;
//line 3
public class Demo
{
public static void main(String[] args)
{
Scanner input = new Scanner("true \n a 123 456.789 hello there\nxyz\n");
//line 10
boolean flag = input.nextBoolean();
//line 11
String s = input.next();
//line 12
int n = input.nextInt();
//line 13
double d = input.nextDouble();
//line 14
String line = input.nextLine();
//line 15
System.out.println( "***"+flag+"***");
//line 16
System.out.println( "***"+s+"***");
//line 17
System.out.println( "***"+n+"***");
//line 18
System.out.println( "***"+d+"***");
//line 19
System.out.println( "***"+line+"***");
//line 20
}
}
 To define an object, we use the new expression:
className objName=new className(initializers);
The new expression creates an object of type className and initializes the object with the initializers
supplied in parenthesis, and then returns the address of the newly constructed and initialized object.
//Example 2-4-7
//Demo.java
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner input = new Scanner("11 12.2 13 \n 14.2 15.5 \n 16 17 18");
System.out.println("***"+input.nextDouble()+"***");
System.out.println("***"+input.nextLine()+"***");
System.out.println("***"+input.nextInt()+"***");
//line 11
}
}
Using Scanner to read from the keyboard

Once you understand how a Scanner reads from a String, then it is straightforward to use a Scanner to
read from the keyboard or a disk file. The key is, the buffer of a Scanner object is filled with the
characters of the input String if the Scanner is constructed from ___________________, it is filled
with the characters entered via the keyboard if the Scanner is constructed from
___________________, and it is filled with the characters in the disk file if the Scanner is constructed
from ___________________. The input operations work the same way in all 3 situations.
//Example 2-4-8
//Demo.java
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int num1=0, num2=0, num3=0, sum=0;
Scanner input = new Scanner(System.in);
//line 9
System.out.println("Enter 3 integers separated by white space:");
num1 = input.nextInt();
num2 = input.nextInt();
num3 = input.nextInt();
sum=num1+num2+num3;
System.out.println("The sum is "+sum);
}
}
Case Study -- Fahrenheit to Celsius

Write a program that converts a Fahrenheit degree to Celsius using the formula:
celsius  ( 95 )( fahrenheit  32)
//Example 2-4-9
//FahToCel.java
import java.util.Scanner;
public class FahToCel
{
//Desc: Convert a degree Fahrenheit to degree Celsius
//Input: A degree Fahrenheit entered via the keyboard.
//Output:The input degree Fahrenheit converted to degree Celsius printed on the screen
public static void main(String[] args)
{
}
}
Programming exercises
1.
Write a console application which reads the radius of a sphere and prints its volume on the screen.
You must write the API for method main. In addition, you must include the following comment at the
top of the program
//Your name
//Your email address
//SphereVolume.java
Hint:
 The formula for the volume of a sphere is: 4 r 3

3
Remember to test your program.
Note:
 You must make the output user-friendly and make sure that only 2 decimal digits at the most are
printed.
2.
Write a console application which reads a degree Celsius and prints the corresponding degree
Fahrenheit on the screen. You must write the API for method main. In addition, you must include the
following comment at the top of the program
//Your name
//Your email address
//CelToFah.java
Hint:
 The formula to convert degree Celsius to degree Fahrenheit is: cel * 9  32
5
Note:
 You must make the output user-friendly and make sure that only 2 decimal digits at the most are
printed.
3.
Write a console application which reads an amount for total inches and prints the corresponding yards,
feet, inches on the screen. For example, 40 inches will be converted to 1 yard, 0 feet, 4 inches. You
must write the API for method main. In addition, you must include the following comment at the top
of the program
//Your name
//Your email address
//InchesToYdFtIn.java
Hint:
 1 foot =12 inches
 1 yard =3 feet
Note:
 You must make the output user-friendly.