Download Lecture2

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
Object-Oriented Programming (Java)
Topics Covered Today
• Unit 1.1 Java Applications
– 1.1.3 Beginning with the Java API
– 1.1.4 Console I/O
2
Java API
• API stands for Application Programming
Interface(应用程序接口).
• Java API 是Java提供给应用程序的类库,这些
库经过仔细的编写,严格地与广泛地测试。
• Most programs use both features from the Java
API and essential language features.
• http://java.sun.com/j2se/1.5.0/docs/api/
3
Package
• The classes in the Java API are grouped into packages.
– Java用包来管理类名空间,为了解决同名的类有可能发生冲
突的问题,包实际提供了一种命名机制和可见性限制机制.
• A package is simply a collection of related classes
– 所有的图形界面的类都放在java.awt这个包中,
– 与网络功能有关的类都放到java.net这个包中。
• The fully qualified name of a class that is part of a
package is the package name and the class name separated
by a dot.
–
java.awt.Color
4
import Statement
• 如果在源程序中用到了除java.lang这个包以外
的类,无论是系统的类还是自己定义的包中的
类,都必须用import语句标识,以通知编译器
在编译时找到相应的类文件。
• 如果要从一个包中引入多个类则在包名后加上
“.*”表示, 如
– import java.awt.Color;
– import java.awt.*;
• Classes java.lang.* are automatically imported
5
Example
import java.lang.String;
Qualified
import java.io.FileWriter;
names
import java.io.IOException;
public class test {
public static void main(String[] args) {
try {
Simple
FileWriter fw = new FileWriter("hello.txt");
name
String h = "Hello"; String w = "World";
fw.write(h+ " " + w); fw.close ();
}
catch (IOException e) {
System.out.println("Error writing to file:" + e);
}
}
}
6
The java.lang.String Class (1)
• Java中没有处理字符串的基本类型,但是有一个String
类可以用来存储和处理字符串。
• String类的成员函数:
– String(). Constructs a new String object that represents an empty
character sequence.
– String(char[] value). Constructs a new String object that
represents the sequence of characters contained in the character
array.
– String(String original). Constructs a new String object that
represents the same sequence of characters as the argument.
– int size(). Obtains the number of characters in the String.
– char charAt(int index). Returns the character at the specified
index.
7
The java.lang.String Class (2)
– boolean equals(Object anObject). Returns true if the
specified Object represents a String with the same sequence
of characters.
– int indexOf(int ch). Returns the index of the first
occurrence of the character.
– int indexOf(String str). Returns the index of the first
occurrence of the String.
– boolean startsWith(String prefix). Checks if the String has
the specified prefix.
– String substring(int beginIndex, int endIndex). Returns a
substring.
8
The java.lang.String Class (3)
• String类的操作:
– String中提供字符串的比较的方法:equals( )和
equalsIgnoreCase( )
– 它们与运算符‘= =’实现的比较是不同的。
• 运算符‘= =’比较两个对象是否引用同一个实例,
• 而equals( )和equalsIgnoreCase( )则比较两个字符串中对应的每个字符
值是否相同。
– 字符串的转化
• java.lang.Object中提供了方法toString( )把对象转化为字符串。
– 字符串"+"操作
• 运算符‘+’可用来实现字符串的连接:
String s = “He is ”+age+“ years old.”;
• 注意:除了对运算符"+"进行了重载外,java不支持其它运算符的重
载。
9
The java.util.StringTokenizer Class (1)
• Tokenizing is the process of breaking a string into
smaller pieces called tokens.
– 例:下面字符串用空格化分,可分为几个字符串?
"This string has five tokens"
• Popular delimiters(分割符) include the white
space, underscore ( _ ) and the comma ( , ).
10
The java.util.StringTokenizer Class (2)
• StringTokenizer类在java.util 包中,常用的方法有:
– StringTokenizer(String str). Constructs a string tokenizer. The
tokenizer uses the default delimiter set, white space.
– StringTokenizer(String str, String delim). Constructs a string
tokenizer. The argument delim contains the character delimiters
for separating tokens.
– boolean hasMoreTokens(). Tests if there are more tokens to
extract.
– String nextToken(String delim). Returns the next token in the
string.
– int countTokens(). Obtains the number of tokens left to be
extracted, not the number of tokens in the string.
11
The java.util.StringTokenizer Class (3)
import java.util.*;
public class ProductInfo {
public static void main(String[] args) {
String data = "Mini Discs 74 Minute (10-Pack)_5_9.00";
StringTokenizer tknzr = new StringTokenizer(data, "_");
String name = tknzr.nextToken();
String quantity = tknzr.nextToken();
String price = tknzr.nextToken();
System.out.println("Name: " + name);
System.out.println("Quantity: " + quantity);
System.out.println("Price: " + price);
}
}
12
Java’s Primitive Types
• 整型:
– byte:8-bit
– short:16-bit
– int:32-bit
– long:64-bit
• 浮点型:
– float:32-bit
– double:64-bit
• 字符型:char 16-bit
• 布尔型:boolean
13
The Wrapper Classes (1)
• 为了保证处理数据的一致性,Java将基本数据类型也封装成了
类,这些类统称为wrapped classes。
– java.lang.Byte
– java.lang.Short
– java.lang.Integer
– java.lang.Long
– java.lang.Character
– java.lang.Float
– java.lang.Double
– java.lang.Boolean
14
The Wrapper Classes (2)
public class WrapperConversion {
public static void main(String[] args) {
Integer objectValue = new Integer(100);
int intValue = objectValue.intValue();
long longValue = objectValue.longValue();
double doubleValue = objectValue.doubleValue();
String stringValue = objectValue.toString();
System.out.println("objectValue: " + objectValue);
System.out.println("intValue: " + intValue);
System.out.println("longValue: " + longValue);
System.out.println("doubleValue: " + doubleValue);
System.out.println("stringValue: " + stringValue);
}}
15
The Wrapper Classes (3)
import java.util.*;
public class ProductInfo {
public static void main(String[] args) {
String data = "Mini Discs 74 Minute (10-Pack)_5_9.00";
StringTokenizer tknzr = new StringTokenizer(data, "_");
String name = tknzr.nextToken();
int quantity = Integer.parseInt(tknzr.nextToken());
double price = Double.parseDouble(tknzr.nextToken());
System.out.println("Name: " + name);
System.out.println("Quantity: " + quantity);
System.out.println("Price: " + price);
}
}
16
Primitives and Wrappers
• Primitives in Java aren't objects at all.
• Wrapper classes are object versions of the
primitive types.
• Things get annoying when you have to go back
and forth between the two - converting a primitive
to its wrapper, using it, then converting the object's
value back to a primitive.
• Happily, Tiger finally takes care of this issue.
17
New Java Language Feature
• Java 5.0 introduced new language features
– http://java.sun.com/j2se/1.5.0/docs/guide/language/
• Autoboxing(自动装箱) /unboxing(自动拆箱)
– Automatically converts primitives (such as int) to
wrapper classes (such as Integer)
– Data value  Object (of matching class)
18
Autoboxing/Unboxing Example(Classical Approach)
• Traditional “boxing” example:
List ssnList = new ArrayList();
...
int ssn = getSocSecNum();
...
Integer ssnInteger = new Integer(ssn);
ssnList.add(ssnInteger);
• Why do I have to convert from int to Integer?
Autoboxing/Unboxing Example(New Approach)
• “Autoboxing” example:
List ssnList = new ArrayList();
...
int ssn = getSocSecNum();
...
ssnList.add(ssn);
• No need for an explicit conversion to Integer.
20
Unboxing(Converting Wrapper Types to Primitives)
• “Autoboxing/unboxing” example:
// Boxing
int foo = 0;
Integer integer = foo;
// Simple Unboxing
int bar = integer;
21
Autoboxing / Unboxing
• The need to explicitly convert between primitive
types and wrapper objects.
– Such as primitive type int, and wrapper object Integer.
– Can’t put primitives into Collections.
• Autoboxing and Unboxing
– Automatic conversion by the compiler
– Eliminates casts
• Compiler performs these conversions for us.
22
Unboxing(Converting Wrapper Types to Primitives)
• Null value assignment:
Integer i = null;
int j = i;
– i is assigned null (which is legal), and then i is unboxed
into j. However, null isn't a legal value for a primitive,
so this code throws a NullPointerException.
23
Incrementing and Decrementing Wrapper Types
• Every operation available to a primitive should be
available to its wrapper-type counterpart, and vice versa:
Integer counter = 1;
while (true) {
System.out.printf("Iteration %d%n", counter++);
if (counter > 1000) break;
}
– Remember that counter is an Integer. So the value in counter
was first auto-unboxed into an int, as that's the type required for
the ++ operator. Once the value is unboxed, it is incremented.
Then, the new value has to be stored back in counter, which
requires a boxing operation.
24
Levels of Java API
• Each JDK defines a standard set of API classes and
methods
• Sun provides standard extensions to the standard API
• Others can and do provide Java APIs
25
Console I/O
Stream
• 在程序中提供一种将数据源连接到应用程序的方
法,这样的方式叫做流(stream)。流是数据的真正
流动.
d
w
o
o
r
l
l
l
e
h
read( )
InputStream
e.g. from disk file
Filter InputStream
27
Stream Input/Output
• Stream
– A connection carrying a sequence of data
• Bytes  InputStream, OutputStream
– Byte streams are used for data-based I/O, called input streams and
output streams
• Characters  FileReader, PrintWriter
– Character streams are used for text-based I/O, called readers and
writers
– From a source to a destination
•
•
•
•
Keyboard
File
Network
Memory
28
Standard Input/Output
• Standard I/O
– Provided in System class in java.lang
– System.in
• An instance of InputStream
• To input bytes from keyboard
– System.out
• An instance of PrintStream
• To allow output to the screen
– System.err
• An instance of PrintStream
• To allow error messages to be sent to screen
29
java.io package
• Class java.io.BufferedReader
– public BufferedReader(Reader in)
• Create a buffering character-input stream that uses a default-sized input
buffer.
– readline(): Read a line of text.
– read(): Read a single character.
• Class java.io.PrintWriter
– public PrintWriter(OutputStream out, boolean autoFlush)
• Create a new PrintWriter from an existing OutputStream.
• Print formatted representations of objects to a text-output stream.
– print(String s): Print a string
– println(String s):Print a string and then terminate the line
30
Template of a class using Console I/O
import java.io.*;
public class AnyClassUsingIO {
private static BufferedReader stdIn = new
BufferedReader(new InputStreamReader(System.in));
private static PrintWriter stdOut = new
PrintWriter(System.out, true);
private static PrintWriter stdErr = new
PrintWriter(System.err, true);
/* other variables */
/* methods */
}
31
4 examples in unit 1.1.4
•
•
•
•
PrintlnDemo.java
PrintDemo.java
Hello.java
ReadThreeIntegers.java
32
Using the printf( ) Convenience Method
• Tiger gives us the ability to type printf( ).
import java.io.*;
public class PrintTester {
public static void main(String[] args) {
String filename = args[0];
try {
File file = new File(filename);
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String line;
int i = 1;
while ((line = reader.readLine( )) != null) {
System.out.printf("Line %d: %s%n", i++, line);
}
} catch (Exception e) {
System.err.printf("Unable to open file named '%s': %s",
filename, e.getMessage( ));
} }}
33