Download OOP_Course03

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

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

Document related concepts
no text concepts found
Transcript
OBJECT ORIENTED
PROGRAMMING
Course 3
Loredana STANCIU
[email protected]
Room B613
THE NUMBERS CLASSES
´
Primitive
P
i iti ttypes tto d
define
fi variables:
i bl
« int i = 2;
« float
fl t j
j;
« double d;
´
Wrapper classes for each of the primitive data types
´ Wrap the primitive type in an object
´ Often, the wrapping is done by the compiler
´
´
´
´
Integer x, y;
x = 12;
y = 15;
System.out.println(x+y);
y
p
( y);
THE NUMBERS CLASSES
´
All of the numeric wrapper classes are
subclasses of the abstract class Number
THE NUMBERS CLASSES
´
Why tto use a Number object
Wh
bj t rather
th th
than a
primitive?
« As
an argument of a method that expects an object
« To use constants defined by the class
class, such as
MIN_VALUE and MAX_VALUE, that provide the
upper and lower bounds of the data type.
type
« To use class methods for various conversions
METHODS IMPLEMENTED BY ALL SUBCLASSES
OF NUMBER
´
Converts the value of this Number object to the
primitive data type returned.
« byte byteValue()
« short
h t shortValue()
h tV l ()
« int intValue()
« long longValue()
« float
fl t fl
floatValue()
tV l ()
« double doubleValue()
()
METHODS IMPLEMENTED BY ALL SUBCLASSES
OF NUMBER
´
Compares this Number object to the argument.
« int
« int
« int
« int
« int
« int
compareTo(Byte anotherByte)
compareTo(Double anotherDouble)
compareTo(Float anotherFloat)
compareTo(Integer anotherInteger)
compareTo(Long anotherLong)
compareTo(Short anotherShort)
METHODS IMPLEMENTED BY ALL SUBCLASSES
OF NUMBER
« boolean
equals(Object obj)
Determines
D
t
i
whether
h th this
thi number
b object
bj t iis
equal to the argument.
´ The methods return true if the argument is not
null and is an object of the same type and with
the same numeric value.
´
CONVERSION METHODS,
METHODS INTEGER CLASS
« static
´
Returns an integer (decimal only).
« String
St i
´
t
toString()
St i ()
Returns a String object representing the value
of this Integer.
« static
´
int p
parseInt(String
g s)
String toString(int i)
Returns a String object representing the
specified integer.
CONVERSION METHODS,
METHODS INTEGER CLASS
« static
´
Returns an Integer object holding the value of
the specified primitive.
primitive
« static
´
Integer
g
valueOf(int i)
Integer valueOf(String s)
Returns an Integer object holding the value of
the specified string representation.
FORMATTING NUMERIC PRINT OUTPUT
´
The java.io package includes a
PrintStream class
« System.out.println(String
s)
« System
System.out.format(String
out format(String format
format,
Object... args)
« System.out.printf(String
System out printf(String format,
format
Object... args)
« System.out.format(Locale
f
(
l l
l, String
i
format, Object... args)
FORMATTING NUMERIC PRINT OUTPUT
´
System.out.format("The
S
t
t f
t(" h value
l
of
f
the float variable is %f, " + "
" the value of the integer " +
, and the " +
" variable is %d,
"string is %s", floatVar,
intVar stringVar);
intVar,
´
http://java.sun.com/javase/6/docs/api/java
/util/Formatter html
/util/Formatter.html
FORMATTING NUMERIC PRINT OUTPUT
int i = 461012;
;
´ System.out.format("The value of
i i
is: %d%
%d%n",
" i)
i);
´ The output:
p The value of i is: 461012
´ float floatVar = 3.14;
´ System.out.format(Locale.FRANCE,
S t
t f
t(L
l FRANCE
"The value of the float variable
is %f%n", floatVar);
´ The output: The value of the float
´
variable is: 3,14
FORMATTING NUMERIC PRINT OUTPUT
long n = 461012;
´ System.out.format(
System.out.format("%d%n",
%d%n , n);
´ System.out.format("%08d%n", n);
´ System.out.format("%+8d%n", n);
´ System.out.format(
System out format("%
%,8d%n
8d%n", n);
´ System.out.format("%+,8d%n", n);
´
461012
00461012
+461012
461 012
461,012
+461,012
FORMATTING NUMERIC PRINT OUTPUT
double pi = Math.PI;
´ System.out.format(
System.out.format("%f%n",
%f%n , pi);
3.141593
´ System.out.format("%.3f%n", pi);
3.142
´ System.out.format("%10.3f%n", pi);
3.142
´ System.out.format(
System out format("%-10
% 10.3f%n
3f%n", pi); 3.142
3 142
´ System.out.format(Locale.FRANCE, 3,1416
¹"%-10.4f%n%n", pi);
« import java.util.
java util *;;
´
ADVANCED MATHEMATICAL COMPUTATION
´
´
´
´
´
´
´
´
´
import ja
java.lang.Math.*;
a lang Math *
int abs(float f)
int round(float f)
int min(int
(
arg1,
g , int arg2)
g )
int max(int arg1, int arg2)
double
double
double
double
exp(double d)
log(double d)
pow(double
p
(
base,
, double exponent)
p
)
sqrt(double d)
ADVANCED MATHEMATICAL COMPUTATION
´
´
´
´
´
´
´
´
double
double
double
double
double
double
double
double
sin(double d)
cos(double d)
tan(double d)
asin(double
(
d)
)
acos(double d)
atan(double d)
toDegrees(double d)
toRadians(double d)
ADVANCED MATHEMATICAL COMPUTATION
´
Random Numbers
N mbers
random() method returns a pseudo-randomly selected
number between 0.0 and 1.0 (exclusively)
´
int number = (int)(Math.random() * 10);
´
SUMMARY OF NUMBERS
´
´
´
´
Wrapper classes
W
l
– Byte,
B
Double,
D bl Fl
Float, Integer,
I
LLong,
or Short – to wrap a number of primitive type in an
object
bj
The Number classes include constants and useful
class methods
To format a stringg containingg numbers for output,
p , yyou
can use the printf() or format() methods in the
PrintStream class
The Math class contains a variety of class methods for
performing mathematical functions
CHARACTERS
´
´
char
h primitive
i iti ttype — Character
Ch
wrapper class
l
The Character class is immutable, so that once it is
created, a Character object cannot be changed.
´
Creatingg an Character object:
j
Character ch = new Character('a');
´
autoboxing or unboxing
autoboxing—or
´
«
«
´
Character test(Character c) {...}
char
h
c = t
test('x');
t(' ')
java.lang.Character
CHARACTERS
boolean
b
l
i
isLetter(char
tt ( h
ch)
h)
´ boolean isDigit(char
g (
ch)
)
´ boolean isWhiteSpace(char ch)
´ boolean isUpperCase(char ch)
´ boolean isLowerCase(char ch)
´ char toUpperCase(char ch)
´ char toLowerCase(char ch)
´ toString(char ch)
´
STRINGS
A sequence of characters — objects in the
Java programming language
´ How to create a String?
´
« String
greeting = "Hello
Hello world!";
world! ;
« String
St i
s = new String(greeting);
St i (
ti )
« char[]
c={'h','e','l','l','o','.'};
« String
g S = new String(c);
g( );
STRINGS
The String class is immutable
´ accessor methods — methods used to obtain
information about an object
´
String palindrome = "Dot saw I
was Tod";
T d"
´ int len = palindrome.length();
p
g
´
STRINGS
´
´
´
´
´
´
char[]
h [] tempCharArray
t
Ch A
= new char[len];
h [l ]
char[] charArray = new char[len];
f
for
(i
(int
t i = 0;
0 i < len;
l
i ) {
i++)
« tempCharArray[i] = palindrome.charAt(i); }
for (int j = 0;
0 j < len; j++) {
« charArray[j] = tempCharArray[len - 1 - j];
}
String reversePalindrome = new
String(charArray);
System.out.println(reversePalindrome);
STRINGS
Concatenate Strings
´ string1.concat(string2);
´ "My name is ".concat("Ana");
´
´
"Hello," + " world" + "!"
to span lines in source files
´ String s="Now
s= Now is the time“
time +
°
" of roses.";
´
CONVERTING BETWEEN NUMBERS AND
STRINGS
´
Converting Strings to Numbers
´
Number.valueOf()
« float
a = (Float.valueOf(args[0]) ).floatValue();
« float
oat b = (Float.valueOf(args[1])
( oat a ueO (a gs[ ]) ).floatValue();
) oat a ue();
´
Number.parsePrimitive()
« float
f
a = Float.parseFloat(args[0]);
0
« float b = Float.parseFloat(args[1]);
CONVERTING BETWEEN NUMBERS AND
STRINGS
´
Converting Numbers to Strings
int i;
´ String s1 = "" + i;
´
´
String s2 = String.valueOf(i);
int i;
´ double d;
´ String s3 = Integer.toString(i);
´ String s4 = Double.toString(d);
´
CONVERTING BETWEEN NUMBERS AND
STRINGS
´
´
public
bli class
l
T
ToStringDemo
St i D
{
« public static void main(String[] args) {
² double
d bl d = 858.48;
858 48
² String s = Double.toString(d);
² int dot = s.indexOf('.');
² System.out.println(dot + " digits before
d i l point.");
decimal
i t ")
² System.out.println( (s.length() - dot 1) + " digits after decimal point
point.");
);
« }
}
MANIPULATING CHARACTERS IN A STRING
String aPal = "Niagara
Niagara. O roar
again!";
´ char aChar = aPal.charAt(9);
´
MANIPULATING CHARACTERS IN A STRING
String aPal = "Niagara
Niagara. O roar
again!";
´ String r =aPal.substring(11,15);
´
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
´ String[] split(String regex)
´
C
a Seque ce subSeque
ce( t
CharSequence
subSequence(int
beginIndex, int endIndex)
´
String trim()
´
String
i
toLowerCase()
()
´
String toUpperCase()
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
´ int indexOf(int ch)
int lastIndexOf(int ch)
´ int
i t indexOf(int
i d Of(i t ch,
h int
i t fromIndex)
f
I d )
int lastIndexOf(int ch, int fromIndex)
´ int indexOf(String str)
int lastIndexOf(String str)
´ int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int fromIndex)
´ boolean contains(CharSequence
(
q
s))
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
´
public class Filename {
« private String fullPath;
« p
private char p
pathSeparator,
p
, extensionSeparator;
p
;
«
public Filename(String str, char sep, char ext) {
² fullPath = str;
² pathSeparator = sep;
² extensionSeparator = ext; }
«
public String
p
g extension()
() {
² int dot =
fullPath.lastIndexOf(extensionSeparator);
² return
t
f ll th
fullPath.substring(dot
b t i (d t + 1)
1); }
«…
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
´
…
«
public String filename() {
² int dot =
fullPath.lastIndexOf(extensionSeparator);
² int sep = fullPath.lastIndexOf(pathSeparator);
² return fullPath.substring(sep + 1,
1 dot); }
«
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
«
«
«
´
}
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
String fpath = "/home/mem/index
html";;
/home/mem/index.html
Filename myHomePage = new Filename(fpath, '/', '.');
Extension = html
´ Filename
Fil
= iindex
d
´
REPLACING CHARACTERS AND SUBSTRINGS
INTO A STRING
String replace(char oldChar, char newChar)
´ String replace(CharSequence target,
q
replacement)
p
)
CharSequence
´ String replaceAll(String regex, String
replacement)
´ String replaceFirst(String regex, String
replacement)
´
COMPARING STRINGS AND PORTIONS OF
STRINGS
´
boolean endsWith(String suffix)
boolean
b l
startsWith(String
t t With(St i g prefix)
fi )
int compareTo(String anotherString)
´ int
i compareToIgnoreCase(String
T I
C
(S i str))
´
boolean equals(Object anObject)
´ boolean equalsIgnoreCase(String anotherString)
´
THE JAVA I/O SYSTEM
import java.io.
java.io.*;;
´ I/O operations based on streams
´
« Input
streams
« Output streams
´
Standard I/O
« System.in
System in
« System.out
« System.err
THE JAVA I/O SYSTEM
´
´
´
IInputt and
d Output
O t t - Source
S
and
dD
Destination
ti ti
The terms "input" and "output" can sometimes be a bit
confusing
Java's IO package concerns with:
«
«
´
the reading of raw data from a source
the writing of raw data to a destination
The typical sources and destinations of data:
«
«
«
«
«
Files
Pipes
Network Connections
In-memory Buffers (e.g. arrays)
S t
System.in,
i System.out,
S t
t System.error
S t
THE JAVA I/O SYSTEM
A program that needs to read data — an input
stream or Reader
´ A program that needs to write data — an output
stream or writer
´ An InputStream or Reader is linked to a
source of data.
´ An OutputStream or Writer is linked to a
destination of data.
´
THE JAVA I/O SYSTEM
´
Java IO Purposes and Features
«
«
«
«
«
«
«
«
«
«
File Access
Network Access
Internal Memory Buffer Access
Inter-Thread Communication (Pipes)
Buffering
Filtering
Parsingg
Reading and Writing Text (Readers / Writers)
Readingg and Writingg Primitive Data ((long,
g, int etc.))
Reading and Writing Objects
THE JAVA I/O SYSTEM
´
Th InputStream
The
S
class:
l
«
«
´
´
´
´
´
the base class of all input streams in the Java IO API
used for reading byte based data, one byte at a time
The FileInputStream class — read the contents of
a file as a stream of bytes
InputStream input = new
FileInputStream("c:\\data\\input-text.txt");
int data = input.read();
while(data != -1)
« {doSomethingWithData(data);
« data = input.read();}
input.close();
THE JAVA I/O SYSTEM
´
´
´
´
´
´
The R
Th
Reader
d iis the
h baseclass
b
l
off allll R
Reader's
d ' in
i the
h Java
J
IO API — BufferedReader
Reader reader = new FileReader();
int data = reader.read();
while(data != -1){
« char dataChar = (char) data;
« data = reader.read(); }
Can be combined with an InputStream — wraped into
InputStreamReader
Reader reader = new
InputStreamReader(inputStream);
THE JAVA I/O SYSTEM
´
´
´
´
´
´
The InputStreamReader
Th
S
d class
l
is
i iintended
t d d tto wrap
an InputStream, thereby turning the byte based
i
input
stream iinto a character
h
b
based
dR
Reader.
d
InputStream inputStream = new
Fil I
FileInputStream("c:\\data\\input.txt");
tSt
(" \\d t \\i
t t t")
Reader reader = new
InputStreamReader(inputStream);
int data = reader.read();
while(data != -1){
1){
« char theChar = (char) data;
« data
d t = reader.read();
d
d() }
reader.close();
THE JAVA I/O SYSTEM
Reading text lines
´ BufferedReader — readLine()
´
« Reads
from an input stream until the line end
« Returns a reference to a String without the line
end or null
« IOException
p
is throwed if no readingg done
´
The constructor needs an object of
InputStreamReader
if reading from a file
« System.in if reading from the console
« FileInputStream
THE JAVA I/O SYSTEM
´
BufferedReader r_in
r in = new BufferedReader(new
InputStreamReader(new
FileInputStream(file name)));
FileInputStream(file_name)));
´
BufferedReader r_in = new BufferedReader(new
(
InputStreamReader (System.in));
´
li = r_in.readLine();
line
i
dLi ()
THE JAVA I/O SYSTEM
´
Th PrintStream
The
i
class:
l
« Enables
the writingg of formatted data to an
underlying OutputStream
« Contains
the print()/println() to print a string
« Contains the powerful format() and printf() methods
´
The constructor needs
Th
d an object
bj
off
FileOutputStream (write a file as a
stream of bytes)
THE JAVA I/O SYSTEM
´
PrintStream w_out = new PrintStream (new
FileOutputStream(file_name));
´
w_out.println(“…”);
´
w_out.print(true);
´
w out print((int) 123);
w_out.print((int)
´
w_out.print((float) 123.456);
´
w_out.printf(Locale.UK, "Text + data: %1$",
123);
´
w_out.close();
THE JAVA I/O SYSTEM
´
Streams and Readers / Writers need to be
closed properly
´
r_in.close( );
´
w out close( );
w_out.close(
´
public static void main (String[
] arg) throws IOException {
´
…
´
}
REFERENCES
´
´
The Java
Th
J
Tutorials.
T
i l Learning
L
i the
h Java
J
LLanguage.
http://java.sun.com/docs/books/tutorial/java/data
/i d h l
/index.html
Java IO Tutorial. http://tutorials.jenkov.com/javaio/index.html