Вы находитесь на странице: 1из 400

32.972.

2-0187
004.43(075)
19

19

. .
Java. - : .
.: , 2011. 400 .
ISBN 978-5-49807-948-6
-
, Java.
, Java,
, ,
Java, , .
.
Java. . , , . , , Java.
.
3-
,
,
.

32.972.2-0187
004.43(075)

. .
, , ,
. , ,

, .

ISBN 978-5-49807-948-6

, 2011


. ..................................9
I. Java........................................... 15
1. Java............................................................................................................. 16
2. Java....................................................................... 49
3. .................................................................................................................... 80
4. ................................................................................................110
5. ...................................................................................153
6. ................................................198

II. Java............... 229


7. ........................................................................................230
8. ..................................................................................................242
9. ........................................................262
10. ..............................................................282
11. -.......................................................................................299
12. ..................................318
................................................................................................................................376
.................................................................................................................................377

. ................. 379
.......................................... 396


. ..................................9
- Java.......................................... 10
Java ++.............................................................................................. 11
.................................................................................................. 12
........................................................................................................................ 12
............................................................................................................... 12
......................................................................................................................... 13

I. Java........................................... 15
1. Java................................................................................ 16
.............................................................................................................. 16
........................................................................................................................... 18
................................................................................. 19
.................................................................................................................. 23
Java.................................................................................................. 25
............................................................................................................... 32
........................................................................................................................................ 48
2. Java.................................................... 49
if().................................................................................................... 49
switch().......................................................................................... 53
for()...................................................................................................... 56
while()................................................................................................. 59
do-while()........................................................................................................ 60
break() continue()................................................................... 61
............................................................................................................... 63
........................................................................................................................................ 78
3. ..................................................................................... 80
........................................................................................ 80
........................................................................... 83
........................................................................................................... 87
............................................................................. 89

............................................................................................................... 92
......................................................................................................................................108
4. ..................................................................... 110
..............................................................................................................110
..........................................................................................114
.......................................................................................................118
.....................................................................................................121
this............................................................................................................124
.............................................................................................................126
...........................................................................................................128
.............................................................................................................129
......................................................................................................................................151
5. ............................................................ 153
.............................................................................................................153
........................................................................................................................156
...................................................................159
........................................................................................164
.............................................................................................................166
......................................................................................................................................197
6. ................................. 198
.............................................................................................................198
...................................................................................200
........................................................................................202
.....................................................................................204
...........................................................208
.......................................................................................212

......................................................................................................215
...........................................................................................................218
.............................................................................................................220
......................................................................................................................................227

II. Java............... 229


7. ................................................................ 230
Java........................................................................................................................230
...........................................................................................................................232
.......................................................................................................235
.................................................................................................239
......................................................................................................................................240
8. ....................................................................... 242
String.......................................................................................................242
toString()...................................................................................................................246
...................................................................................248
...................................................................................................................251

.............................................................................................253
............................................................................................254
StringBuffer................................................................................................................256
........................................................................................259
......................................................................................................................................260
9. ........................................ 262
..............................................................................................262
............................................................................................................264
..........................................................................267
catch{}..........................................................................................268
try.........................................................................................................270
..............................................................273
.........................................................................275
.............................................277
.............................................................................278
......................................................................................................................................280
10. ........................................... 282
Java........................................................................................................282
...................................................................................................................285
........................................................................................290
....................................................................................................293
......................................................................................................................................298
11. -............................................................. 299
.....................................................................................300
System.in.......................................301
Scanner...........................................................305
..................................................................................307
.................................................................................................................310
......................................................................................................................................316
12. ...................... 318
....................................................................................................319
.............................................................................................................323
......................................................................................................326
......................................................................................332
.............................................................................................339
...........................................................................................................................355
..............................................................................................363
......................................................................................................................................375
........................................................................................... 376
............................................................................................ 377

. ................. 379
.......................................... 396

.
Java.
,

- .
Java .
, ,
, . Java. ,
. , , . ,
Java, , , Java, , .
,
. .

,
Java.
.
.
Java
.
.

10

- Java
Java -. ,
, Java, ( ). , -
, , . , . C++, # Java.
C++, C. . ++
# Java. ,
. C++ , ,
. , Java C#,
.
Java SunMicrosystems (
Oracle), C# Microsoft.
Java C# C++
, .
, C#,
, Java .
!
, Java.
Sun Microsystems, Java. 1991 1995.

.
, -
. , , Java (
) .
Java-.
, (, C++)
, Java- -, , Java- ( Java Virtual
Machine, JVM). , Java-
. ,
( ,

Java ++

11

). , , .
, , Java
. Java ,
Hello, world! , . Java
( , ). ,
, ,
.

Java ++
,
C++. , , ,
C++ Java ,
. . Java, Java C++. 3,
. C++ Java .
, .
, Java .
, Java ,
. , ++ . Java ,
. , ,
, . , Java
. , , .
: Java
. , . ++,
.
. Java
, .
.
.
Java ,
, .

12

++ Java. , ++, Java .


,
.
, ++ Java ,
. , , ++,
Java . ++ , Java.


SunMicrosystems. ,
,
. ( )
www.java.
com, Java.
Java, JDK ( Java
Development Kit Java) JRE ( Java Runtime Environment
Java). www.java.com (
www.oracle.com). , .
- . NetBeans,
www.netbeans.org.
, JDK JRE. Eclipse, www.eclipse.org. ,
.
Java .


www.
vasilev.kiev.ua. ,
vasilev@univ.kiev.ua alex@vasilev.kiev.ua.



www.piter.com www.vasilev.kiev.ua.

13

Java -
( ) , .
- , ,
.
.

.
, .


,
comp@piter.com ( , ).
!
-
http://www.piter.com.

I. Java

1. Java
, ! -.
.

, Java -. ,
. Java, , .
Java
. .
,
.
Java, , 4, , , -
( ). , , , , , , -
Java. , ,
(, C++), Java.


, ! , !

, . , ,
, ,
.

17

1.1.
class Intro{
public static void main(String[] args){
System.out.println(" Java!");
}
}

(, NetBeans)
Java!. . , , ++.
-, , Java ( C++ C#) .
( {) ( })
. . , ,
, .
, . class.
.
. , class Intro{...} Intro.
Intro main()
(
, ). .
, Java-
main(). , main() , .
main() ( main()
). main() ,
.
public, static void main() : public , static (
), void . ,
(public) , 6, . (static) 4, .
, (
main()), .
String[] args main() : args, ( String). String

18

1. Java

(.8). .

4, .
String args.
, ++, . ,
, :
:
class _{
public static void main(String[] args){
_
}
}

( _) , , . , _, .

System.out.println(" Java!").
Java.
println() ( ) " Java!". .
- out
System. - , . , System.out.println(),
, , ..
, println(), , 8, String
StringBuffer.

1.1, , NetBeans.

. !

, ,

19

. , , . Java
.
1. .
( //). ,
, .
2. . /* */. ,
/* */, .
3. .
/**
*/.
.
.
. , .


,
, .

, . .
Java . ,

. Java .
.
. , ,
.

. ,
. , , .
Java 4,
. ,
, , .
.
Java : ,
( ),

20

1. Java

,
. Java .1.1.
1.1. () Java

()

byte

128 127

Byte

short

16

32768
32767

Short

int

32

2147483648
2147483647

Integer

long

64


9223372036854775808
9223372036854775807

Long

float

32

.

3,41038 3,41038

Float

double

64

.

1,710308 1,710308

Double

char

16


().
0 65536 (
)

Character

boolean

.
Boolean
: true
() false ()

- .
- , .
. .
Java : byte, short, int long.
, . 8 byte 32
long ( 8).
. ,
, , .
float double.
.
:

21

. .
, double,
float, double .
double.
Java ( char) 16,
, . ,
, Java , .
8- ISO-Latin-1 0 255,
0 127 ASCII.
boolean, : true false. ( ) boolean - .
Java-.
,
.
.
. . , ,
.
" Java!". , ,
, ,
0 9. .
.
( , !),
true false.
Java,
.
. , intn n int.
.
Java =. , 12:
int n;
n=12;


int n=12. ,
,

22

1. Java

.
, :
long n, m;
int x, y=3, z=5;
char sym='a';


long, int, . sym a( ). , , . ,
, ( { }).

. , () , (
). ,
, 1.2.
1.2.
class VarDemo{
public static void main(String[] args){
// :
byte age=34;
char sex='';
double weight=103.6;
int height=182;
// :
System.out.println(" :");
System.out.println(": "+age+" ");
System.out.println(" (/): "+sex+".");
System.out.println(": "+weight+" ");
System.out.println(": "+height+" ");
}
}

:
:
: 34
(/): .
: 103.6
: 182

.
( , , ).

23

( ) .
, ,
. .
0 7 . , 012 10.
0x.
0 9 F. , 0x12
18.
, '\xxx' Unicode, '\uxxx' ( x ).

. . , :
int double. .
double
int .
, . , . ,
( Java),
. , ,
, .
. .
, , .
, , .
(, )
. ,
.

24

1. Java

byte, short char int.


long,
long.
float,
float.
double,
double.
. , , , () 2?
int, long , , double? .
, ,
int.
, , double.
, , , , . ,
:
byte a=1,b=2,c;
// :
c=a+b;

.
byte, a+b int. int
byte. Java
, .
, :
float x=2.7;

, 2.7,
x float,
double.
, Java

.
, . ,
:

Java

25

bytea=1,b=2,c;
// :
c=(byte)(a+b);

(byte)(a+b) a b, byte. , .
, ,
. .
. ,
. , L
(, 123L) , long, F , (, 12.5F),
, float.
:
float x=2.7F;
float x=(float)2.7;

, .
Java, ++, .

, , . :
inta=3,b=4;
intc=a*a+b*b;

c a*a+b*b,
25. , , .

Java
,
, ,
, .

Java : , , . . . .1.2.

26

1. Java

1.2. Java

. a+b a b

. a-b a b

. a*b a b

. a/b a b.

. a%b
a b

+=

(
)

. a+=b
a=a+b

-=

(-
. a-=b
) a=a-b

*=

(-
. a*=b
) a=a*b

/=

(
)

. a/=b
a=a/b

%=

( )


. a%=b a=a%b

++

. a++ ( ++a)
a=a+1

--

. a-- ( --a)
a=a-1

. /. , .
:
inta=5,b=2;
doublex=a/b;

x 2.0, 2.5,
. , a/b.

Java

27

, . double
x.
,
double ( float). , :
inta=5,b=2;
doublex=(double)a/b;

x 2.5.
Java, ++,
. op , ,
,
op=. , op,
xop=y x=xopy.

(++) (--).
,
. , x++ x=x+1,
x-- x=x-1.
( : x++ x--), ( :
++x --x). , .
,
. , , .
, , . :
int n,m;
n=10;
m=n++;

n 11,
m 10. m=n++
n 10. m=n++
,
m, n .
:
int n,m;
n=10;
m=++n;

28

1. Java

(n m) 11.
m=++n , n, n m.
.
boolean. Java .1.3.
1.3. Java

&

. A&B true, true.


false

&&

. , &, , false,

. A|B true,
true. false

||

. , |, , true,

. A^B true, true.


false

. !A
true, A false. A true, !A
false


.
.1.4 , Java.
1.4. Java

==

A==B true,
A B .
false

Java

29

<

A<B true,
A B.
false

<=

A<=B true,
A B. false

>

A>B true,
A B.
false

>=

A>=B true,
A B.
false

!=

A!=B true,
A B . false

.

.
.
.
( ) . , .
bn bn 1 ...b2 b1b0 (bi 0 1,
bn= 0) :
b0 2 0 + b1 21 + b2 2 2 + ... + bn 1 2 n 1 + bn 2 n .

( . ), , ( ).

,
.

( ).
Java .1.5.

30

1. Java

1.5. Java

&

. .
1,
1. 0

. .

1,
1. 0

.

. 1,
1.
0

.
: 0 1, 1 0

. ,
( )
,
( ). .
,

. ,
( ) , (
).
.
,

>>>

. , ( ) , (
).
. ,

&=

A&=B
& A=A&B

|=

A|=B
| A=A|B

>>

<<

Java

31

^=

A^=B
^ A=A^B

>>=

- A>>=B
>> A=A>>B

<<=

- A<<=B
<< A=A<<B

>>>=

- A>>>=B
>>> A=A>>>B

, ,
.
, Java ( ). ?:.
:
?_1:_2

,
. - true,
_1. - false,
_2.
( =). Java
. x=y
. y, x .
, , ,
, Java x=y=z. z
y, y x.
,
op=. , A op=B A=AopB, .
Aop=B AopB, A A.
A , , ,
A=A op B ,

32

1. Java

. :
bytea=10,b=20;
// :
a+=20;
// :
a=a+b;

a+=20 , a=a+b .
20 int byte
+=. a+b int, int byte .
. 1.6
Java.
1.6. Java

(), []

++, --, ~ !

*, / %

+ -

>>, << >>>

>, >=, <= <

== !=

&

10

11

&&

12

||

13

?:

14

= op=

( )
.
,
.


, Java
.

33



, . , m,
V, a, .
, , ,
.
g .

. , ( ) :
Vm cos()
x(t ) =
(1 exp(t /m)) .

( ) :
y(t ) =

m(V sin() + mg )

(1 exp(t /m))

mgt
.

g .
. 1.3.
1.3.
class BodyPosition{
public static void main(String args[]){
// :
double g=9.8;
// "":
double pi=3.141592;
// ( ):
double alpha=30;
// ( ):
double m=0.1;
// ( */):
double gamma=0.1;
// ( /):
double V=100.0;
// ( ):
double t=1.0;
// ( ):
double x,y;
// :
alpha/=180/pi;

34

1. Java

1.3 ()
// :
x=V*m*Math.cos(alpha)/gamma*(1-Math.exp(-gamma*t/m));
y=m*(V*Math.sin(alpha)*gamma+m*gamma)/gamma/gamma*(1-Math.exp(-gamma*t/m))-m*g*t/
gamma;
// :
System.out.println(" t="+t+" :\nx="+x+" \ny="+y+" ");
System.out.println(":");
System.out.println(" alpha="+alpha/pi*180+" ");
System.out.println(" V="+V+" /");
System.out.println(" gamma="+gamma+" */");
System.out.println(" m="+m+" ");
}}

:
t=1.0 :
x=54.743249662890555
y=21.86923403403938
:
alpha=30.0
V=100.0 /
gamma=0.1 */
m=0.1


, . Math. Java
, , , , .
, Math.cos(). , Math.sin() Math.exp()
. (), , .
: ,
(
g, V, alpha, , gamma, m). ,
t, , . x y
.

, ..


, , , .

35

(
) , . ,

( ).
S1,
S2,
V1 V2, V,
V2 :
V2 =

S2
.
(S1 + S 2 ) V S1 V1

, , ,
. , , . , ,
,
. .
.
, . , T = (S1 + S 2 ) V ,
t = S1 V1. :
V2 =

S2
.
T t

1.4
.
1.4.
class FindV{
public static void main(String args[]){
// ():
double S1=100;
double S2=200;
// (/):
double V1=80;
// (/):
double V=48;
/* ,
:*/
double V2,T,t;
// ():
T=(S1+S2)/V;

36

1. Java

1.4 ()
// ():
t=S1/V1;
// (/):
V2=T>t?(S1+S2)/(T-t):-1;
System.out.println(" :");
// :
System.out.println(V2<0?" !":V2+" /");}
}

:
:
60.0 /

( V) 240
( ), :
:
!


:
V2=T>t?(S1+S2)/(T-t):-1

: , T t
. ,
. , V2
-1.
. , .
, V2,
, " !".
:
System.out.println(V2<0?" !":V2+"/")

println() V2<0?" !":V2+"/",


.
V2 " !",
, (
) "/".


.
,

37

, .
, ,
.
:
G 6, 672 10 11 2/2.
:
M 5, 96 10 24 .
:
R = 6, 37 10 6 .
T ( ), H
:
H=

GMT 2
4 2

R.

1.5.
1.5.
class FindH{
public static void main(String args[]){
// (^2/^2):
double G=6.672E-11;
// ():
double M=5.96e24;
// :
double R=6.37E6;
// ():
double T=1.5;
// :
double H;
// :
T*=3600;
// :
H=Math.pow(G*M*T*T/4/Math.PI/Math.PI,(double)1/3)-R;
// :
H=(double)(Math.round(H))/1000;
// :
System.out.println(" : "+H+" ");}
}

:
: 277.271

38

1. Java

,
,
E ( e) . ( T) ,
T*=3600. :
H=Math.pow(G*M*T*T/4/Math.PI/Math.PI,(double)1/3)-R

pow()
. ,
. pow()
Math, . PI ( Math.PI) . , - ,
.
, (double).
H
. Math.round() 1000 .
Math.round() , 1000 .
(double), H ,
.


, . , z= x+ iy,
x y , i2= 1. Re(z)= x
, Im(z)= y
.
r = x 2 + y 2 . z= rexp(ij)= rcos( j)+ irsin( j), r j x y
x= rcos( j) y= rsin( j).
z= x+ iy n, zn= rnexp(inj)= rncos(nj)+
+irnsin(nj).
. 1.6.
1.6.
class ComplNums{
public static void main(String args[]){

39

double x=1.0,y=-1.0;
int n=5;
double r,phi;
double Re,Im;
r=Math.sqrt(x*x+y*y);
phi=Math.atan2(y,x);
Re=Math.pow(r,n)*Math.cos(n*phi);
Im=Math.pow(r,n)*Math.sin(n*phi);
System.out.println("Re="+Re);
System.out.println("Im="+Im);}
}

.
, .
x y
. n , . Re Im .
r phi double .
Math.sqrt().
Math.atan2().
atan2() ,
. , , , , .
Math.
pow().
, , .

- . :
Re=-4.000000000000003
Im=4.000000000000001

,
.


. ( )
. ,

40

1. Java

, . , () .
,
( t= 0) V, a,
:
x(t) = tV cos(a).
, , :
y(t ) = (t T )V sin() g (t T ) 2 2 .
T .
T0 = 2V sin() g , :
t
T = T0 .
T0
. 1.7.
1.7.
class FindCoords{
public static void main(String args[]){
// , /^2:
double g=9.8;
// , /:
double V=10;
// :
double alpha=30;
// :
double t=5;
// :
double T0,T,x,y;
//
alpha=Math.toRadians(alpha);
// :
T0=2*V*Math.sin(alpha)/g;
// :
T=T0*Math.floor(t/T0);
// :
x=V*Math.cos(alpha)*t;

41

// :
y=V*Math.sin(alpha)*(t-T)-g*(t-T)*(t-T)/2;
// :
x=Math.round(100*x)/100.0;
y=Math.round(100*y)/100.0;
// :
System.out.println("x("+t+")="+x+" ");
System.out.println("y("+t+")="+y+" ");}
}

:
x(5.0)=43.3
y(5.0)=0.46

( g), ( V), , ( alpha), , ( t).


T0 T
. x y
( ).
, . alpha=Math.toRadians(alpha),
toRadians(),
.

T0=2*V*Math.sin(alpha)/g.
T=T0*Math.floor(t/T0). floor(), , .
:
x=V*Math.cos(alpha)*t
y=V*Math.sin(alpha)*(t-T)-g*(t-T)*(t-T)/2

:
x=Math.round(100*x)/100.0
y=Math.round(100*y)/100.0

,
. round(),
. .

42

1. Java


:
a cos( x) + b sin( x) = c .
, , :
sin( x + ) =
sin() =

c
a 2 + b2

.
a 2 + b2
n :

a
x = arcsin
2
2
a +b

c
+ (1) n arcsin

2
2

a +b

+ n .

, 1.8, a, b c
n= 0 , (, ):

c
x = arcsin
2
2
a +b

a
arcsin

2
2

a +b

a2+ b2= c2.


, . ,
a = b = c = 0 (
x) .
1.8.
class FindRoot{
public static void main(String args[]){
// :
double a=5;
double b=3;
double c=1;
// :
double alpha;
// - :
boolean state;
// :
alpha=Math.asin(a/Math.sqrt(a*a+b*b));
// :
state=a*a+b*b>=c*c;
// :
System.out.println(" a*cos(x)+b*sin(x)=c");

43

System.out.println(":");
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.print(" x: ");
// :
System.out.println(state?Math.asin(c/Math.sqrt(a*a+b*b))-alpha:" !");
}}

.
.
println() :
state?Math.asin(c/Math.sqrt(a*a+b*b))-alpha:" !"

, state. state=a*a+b*b>=c*c. true


, , false .
state true, Math.asin(c/Math.sqrt(a*a+b*b))-alpha,
alpha alpha=Math.asin(a/Math.
sqrt(a*a+b*b)) . asin() sqrt() .
,
.
( state) false, " !".
, println() ,
.
:
a*cos(x)+b*sin(x)=c
:
a=5.0
b=3.0
c=1.0
x: -0.8580262366249893

, :
a*cos(x)+b*sin(x)=c
:
a=5.0
b=3.0
c=10.0
x: !

44

1. Java

, ,
.


,
( char) (int).
, int Java
32 , Unicode 16 . , ,
int, , , ( char).
:
16 , 16
. , ,
1.9.
1.9.
class CharsAndInts{
public static void main(String args[]){
// :
int number;
// :
char symbA='',symbB='';
// :
char SymbA,SymbB;
// :
number=((int)symbB<<16)+((int)symbA);
// :
System.out.println(" : \'"+symbA+"\' \'"+symbB+"\'.");
System.out.println(" : "+number);
// :
SymbB=(char)(number>>>16);
SymbA=(char)(number^((int)SymbB<<16));
// :
System.out.println(" :");
System.out.println(" \'"+SymbA+"\' \'"+SymbB+"\'.");}
}

number
, symbA symbB
char. number, : number
, SymbA SymbB
char.

45

number :
number=((int)symbB<<16)+((int)symbA)

.
((int)symbB<<16)
16 () , symbB.
(int) . , (int)symbB ,
<< 16
16 . , symbA.
((int)symbA) .
.

. SymbB=(char)(number>>>16) SymbB. , number>>>16 16 number
( ), (,
symbB). .
, :
SymbA=(char)(number^((int)SymbB<<16))

(int)SymbB<<16)
, 16. , number, , 16 , number .
16 . ^ ( ). ,
, . , ,
, 16, .
(char) . .
:
: '' ''.
: 72025104
:
'' ''.

, ,
.
, .

46

1. Java


. , ,
.
. ,
, , . ,
,
.
R1, R2
R3, R, ,
, ,
:
R1R 2
RR 3
.
r=
+
R1 + R 2 R + R 3
,
, ,
. 1.10.
1.10.
class Resistors{
public static void main(String args[]){
// ():
double R1=3,R2=5,R3=2,R=1;
// ():
double r1,r2,r3;
// :
boolean A,B;
// :
r1=R2*R3/(R2+R3)+R1*R/(R1+R);
r2=R1*R3/(R1+R3)+R2*R/(R2+R);
r3=R2*R1/(R2+R1)+R3*R/(R3+R);
// :
A=(r1<=r2)&&(r1<=r3);
B=(r2<=r1)&&(r2<=r3);
// :
System.out.println(" :");
System.out.println(" R1="+R1+" ");
System.out.println(" R2="+R2+" ");
System.out.println(" R3="+R3+" ");
System.out.println(" R="+R3+" ");

47

// :
System.out.print(" ");
System.out.print(A?"":B?"":"");
System.out.println(" !");}
}

:
:
R1=3.0
R2=5.0
R3=2.0
R=2.0
!

R1, R2, R3, R


double, . r1, r2 r3 double
.
A B ( boolean). A=(r1<=r2)&&(r1<=r3) B=(r2<=r1)&&(r2<=r3).
A true , ( )

. B true
, ( ) . ,
false,
.
A B .
, . . (
) println()
A?"":B?"":"",
. A (
) true, "".
. B?"":"". , B true, "", "".
( ) ,
.

48

1. Java

1. Java -.
,
, . main().
.
2. main() .
. ( ).
.
3. .
.
Java , .
,
.
4. Java , ,
.
, , , .
, , , .
, , ( ) .
( ). ()
,
.
5. Java ,

, . , x=xopy
xop=y, op
.
6. Java ,
.
. .

2. Java
! !


. Java , .
.

if()
, .
, .

. -

, Java , . if().
:
if(){_1}
elase{_2}

if() . , if. ( true),


, if()
( _1). ,
if false, , else (
_2). . .
-, , .

50

2. Java

,
,
.
-, else . if() :
if(){}

,
if. , if . ,
.
if().
Java : else
..
:
if(_1){_1}
else if(_2){_2}
else if(_3){_3}
...
else if(_N){_N}
elase{}

. _1. ,
_1. _1 , _2. _2. _3 ..
_N ,
else.
, C++,
, , if(), ,
( boolean). ++,
if() .
Java
!
Java.
2.1 , .
2.1. if()
class UsingIf{
public static void main(String[] args){
int x=3,y=6,z;

if()

51

// :
if(x!=0){
z=y/x;
System.out.println(" z="+z);}
else System.out.println(" !");
}
}

x, y z.
.
x
( x!=0). , z y x.
z.
( x ),
" !". 2.1
z=2.
if() 2.2.
2.2. if()
class UsingIf2{
public static void main(String[] args){
int x=3,y=6,z;
// :
if(x!=0){
z=y/x;
System.out.println(" z="+z);
// :
return;}
System.out.println(" !");
}
}

, ,
. . , else
.
, x , z=y/x z, "z=" .
return.
x ,
, System.out.println(" !"),

52

2. Java

. ,
! ,
.
, 2.2, z=2.
if() 2.3.
2.3. if()
class UsingIf3{
public static void main(String[] args){
int a=0;
// a 0:
if(a==0){System.out.println(" !");}
// a 1:
else if(a==1){System.out.println(" !");}
// a ( 2 0):
else if(a%2==0){System.out.println(" !");}
// :
else {System.out.println(" !");}
System.out.println(" !");
}
}

main() a.
. !.
a 1, !. ! ,
a .
a a 2 (
0).
!.
. ,
. , System.out.println(" !") else
.
if() ,
if()
switch().

switch()

53

switch()
. .
: ?
! !

switch() ,
, .
. switch() :
switch(){
case _1:
//_1
brake;
case _2:
//_2
brake;
...
case _N:
//_N
brake;
default:
//
}

switch
, (). ,
, case.
case. case break. switch() , .
default(). , break
. , case default, ,
.
switch().
switch() .
, . ,
case,
default ( default ,
switch()). ,
case.
switch() break(). , break case
, -

54

2. Java

switch(). case.
, , . ,
case(), .
switch 2.4.
2.4. switch()
class UsingSwitch{
public static void main(String[] args){
char s='';
System.out.print(" : ");
// :
switch(s){
case '':
System.out.println("");
break;
case '':
System.out.println("");
break;
case '':
System.out.println("");
break;
default:
System.out.println(" ");
}
System.out.println(" !");
}
}

main() UsingSwitch s char. . : , .


System.out.print(":") , print() println(). switch()
s. ,
. ,
System.out.println(" ") .
. s='' :
:
!

switch()

55

, , -, s , -,
s '', :
:
!

,
. 2.5.
2.5. switch
class UsingSwitch2{
public static void main(String[] args){
char s='';
System.out.print(" : ");
// :
switch(s){
case '':
case '':
System.out.println("");
break;
case '':
case '':
System.out.println("");
break;
case '':
case '':
System.out.println("");
break;
default:
System.out.println(" ");
}
System.out.println(" !");
}
}

case. :
case '':
case '':
...

, ( s) '', break, , , s
''.

56

2. Java

for()
.

. Java . for().
for() :
for(;;){
//
}

for , , . . . ,
( ), . ,
. , .
. .
, for
, .
, .
.
: .
. ( true),
( ). .
, , ( ), .. ,
false.
. ,
.
2.6.
2.6. for()
class UsingFor{
public static void main(String[] args){

for()

57

// :
int i;
// :
int sum=0;
// :
for(i=1;i<=100;i++){
sum+=i;}
System.out.println(" 1 100: "+sum);}
}

1 100. sum,
. . i.
. ( ) 1. i<=100,
, 100. sum
i.
i++ .
. :
1100: 5050

, i++ i+=2. ,
. 2.7.
2.7.
class UsingFor2{
public static void main(String[] args){
// :
int sum=0;
// :
for(int i=1;i<=100;i+=2){
sum+=i;}
System.out.println(" 1 100: "+sum);}
}

:
1 100: 2500

,
. 2.8

58

2. Java

,

.
2.8.
class UsingFor3{
public static void main(String[] args){
int sum,i;
// :
for(sum=0,i=1;i<=100;sum+=i,i+=2);
System.out.println(" 1 100: "+sum);}
}

i sum .
. . :
sum+=i, sum
i, i+=2, . ,
. , . .
sum i ,
. i
, ,
sum, .
.
sum+=i i+=2 , ,
sum. 1, 3.
,
. ,
:
System.out.println(" 1 100: "+sum)


.
, ,
sum.
. 2.9 ,

. , .
2.9.
class UsingFor4{
public static void main(String[] args){

while()

59

int sum=0,i=1;
// :
for(;i<=100;){
sum+=i;
i+=2;}
System.out.println(" 1 100: "+sum);}
}

i sum . , (
).
. . i+=2, , .
, , , , .
2.10.
2.10.
class UsingFor5{
public static void main(String[] args){
int sum=0,i=1;
// :
for(;;){
sum+=i;
i+=2;
// :
if(i>100) break;}
System.out.println(" 1 100: "+sum);}
}

, . .
if(i>100)break
. ,
, break .

while()
,
.

for() while() ( do-while(), -

60

2. Java

).
while():
while(){
//
}

while .
. , .
..
for() while() ,
, , ,
. while()
. , for(),
while(). ,
2.11
while().
2.11. while()
class UsingWhile{
public static void main(String[] args){
int sum=0,i=1;
// :
while(i<=100){
sum+=i;
i+=2;}
System.out.println(" 1 100: "+sum);}
}

, .

do-while()
? !
? !

/ -

do-while() while().
:
do{
//
}while();

break() continue()

61

, do. , while. ,
. . ,
do-while() while(). 2.12
do-while() .
2.12. do-while()
class UsingDoWhile{
public static void main(String[] args){
int sum=0,i=1;
// :
do{
sum+=i;
i+=2;}while(i<=100);
System.out.println(" 1 100: "+sum);}
}

,
1 100.

break() continue()
.

Java, ++, goto().


Java .
break() continue().
break() . . break()
, ,
, (,
).
continue() . continue() ,
. , continue()
, .

62

2. Java

, , ,
. .
2.13.
2.13.
class LabelsDemo{
public static void main(String[] args){
MyLabel:
for(int i=1;i<=100;i++){
for(int j=1;j<=100;j++){
if(i!=j) continue;
if((j%3==0)||(i%2==0)) break;
if(i+j>20) break MyLabel;
System.out.println(i+":"+j);}
}}}

.
1 100 .
MyLabel.

System.out.println(i+":"+j), i j . i!=j. , continue
. , .
. , (j%3==0)||(i%2==0). , j 3 i 2.
break
. ,
. , i+j>20
( ), break MyLabel
, MyLabel,
. :
1:1
5:5
7:7

, 3 2
20.

63


, .


Java Math.exp(),
x ex,
e= 2,718281828 . ,
:
ex =

xk
x2 x3
=1+ x +
+
+ ...
2! 3!
k =0 k !

, ,

, . 2.14 , . .
2.14.
class MyExp{
public static void main(String args[]){
// :
int N=100,k;
// ,
// :
double x=1,s=0,q=1;
// :
for(k=0;k<=N;k++){
s+=q;
q*=x/(k+1);}
// :
System.out.println("exp("+x+")="+s);}
}

,
( ):
exp(1.0)=2.7182818284590455

, .
0 N (
100). .
s+=q s ( )
. s

64

2. Java

q, q*=x/(k+1)
-. q x (k+1). - ,
. , N
xk
exp( x)
, k- k =0 k !
k
x
x k +1
q k =
. (k+ 1)- q k +1 =
.
k!
(k + 1)!
q k +1
x
=

k-
qk
(k + 1)
x (k+ 1).


, , . 2.15
,
. ,
.
2.15.
class Fibonacci{
public static void main(String args[]){
// :
int N=15,a=1,b=1;
// :
int i;
System.out.println(" :");
// :
System.out.print(a+" "+b);
// :
for(i=3;i<=N;i++){
b=a+b;
a=b-a;
System.out.print(" "+b);}}
}

:
:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

N ( ), a b,

.
. .

65


. , ,
(b) (a) , b=a+b .
a ,
b. b b a,
b a a.
a=b-a. b
System.out.print(" "+b).


-
. , .
. , ,
. 1/2, /4. ,
. ,
. , .
, /4. ,
,
. , .
= 3,14159265 ( )
- ( ), , ,
, 4 , , .
, 0 1. ,
.
,
. , . 2.16 , .
2.16.
class FindPi{
public static void main(String args[]){
// :
int N=100000;
// :
int i,j;

66

2. Java

2.16 ()
// :
long count=0;
// "":
double x,y,Pi;
// :
for(i=0;i<=N;i++){
for(j=0;j<=N;j++){
x=(double)i/N;
y=(double)j/N;
if((x-0.5)*(x-0.5)+(y-0.5)*(y-0.5)<=0.25) count++;
}
}
// "":
Pi=(double)4*count/(N+1)/(N+1);
// :
System.out.println(" "+(long)(N+1)*(N+1)+" :");
System.out.println(Pi);}
}

,
:
10000200001 :
3.141529585494137

N, . (N+1)*(N+1).
. ,
. count,
, long. i j, x y Pi .
x=(double)i/N y=(double)j/N , i- j- . , (double)
.
(0,5, 0,5), 0,5, , (x,y)
( ) ( x 0, 5) 2 + ( y 0, 5) 2 0, 5 2 .
, , count .
Pi=(double)4*count/(N+1)/(N+1). . (N+1)*(N+1),

67

, (long). , N
int,
(N+1)*(N+1).
,
. , - ,
.
.
, ,
. , ,
0 2 :
(1) n +1
nx
sin .
n
2
n =1

x = 4

(1) k
. k = 0 2k + 1
, 2.17,
.

x= , = 4

2.17.
class FindPi2{
public static void main(String args[]){
// :
int N=5000000,k;
// :
double Pi=0,q=4;
// "":
for(k=0;k<=N;k++){
Pi+=q/(2*k+1);
q*=(-1);
}
// :
System.out.println(" "+N+" :");
System.out.println(Pi);}
}

:
5000000 :
3.1415928535897395

, , ,
.

68

2. Java

.
, :
= 2

2
2

2
2+ 2

...

2+ 2+ 2

2.18 ,
.
2.18.
class FindPi3{
public static void main(String args[]){
// :
int N=20,k;
// :
double Pi=2,q=Math.sqrt(2);
// "":
for(k=1;k<=N;k++){
Pi*=2/q;
q=Math.sqrt(2+q);}
// :
System.out.println(" "+N+" :");
System.out.println(Pi);}
}

:
20 :
3.1415926535886207

,
.
, , ,
. Pi,
2. ,
. ,
, 2
.
q 2 .
. Pi*=2/q - Pi, q=Math.sqrt(2+q) .

69


. x= f(x),
x,
. x
x 0, x= x 0. . n-
x n, x n + 1 x n + 1= f(x n).

, , :
df ( x)
< 1.
dx
2.19 , x 2 + 10
x =
7
.
x = 2 x = 5. x = f(x),
x 2 + 10
df ( x) 2 x
=
.
,
f ( x) =
7
dx
7
, 2,5< x< 2,5, x= 2.
2.19.
class MyEquation{
public static void main(String args[]){
// :
double x0=0;
// :
double x,f;
// :
double epsilon=1E-10;
// :
int Nmax=1000;
// :
int n=0;
// :
f=x0;
do{
// :
n++;

70

2. Java

2.19 ()
// :
x=f;
// ():
f=(x*x+10)/7;}
// :
while((n<=Nmax)&&(Math.abs(x-f)>epsilon));
// "" :
x=f;
// :
System.out.println(" :");
System.out.println("x="+x);
System.out.println(" : "+(n+1));}
}

,
.
Nmax.
epsilon. ,
.
| x n +1 x n | . , , ( ).
, :
( x) ( f). x
x=f, , f, f=(x*x+10)/7. (n<=Nmax)&&(Math.
abs(x-f)>epsilon). true,
n Nmax x-f
epsilon.
:
:
x=1.9999999999205635
: 42

- ,
epsilon.


, , a x 2+ b x+ c= 0. x =

b b 2 4ac
,
2a

71

. ,
a, b c .
,
.
a= 0. x 2. bx+ c= 0.
,
.
b ( , a= 0), x= c/b. b= 0, :
c 0 , c= 0.
a 0, ,
D = b 2 4ac . D< 0
. D= 0,
b
x =
. , D> 0
2a
b D
x =
.
2a
, 2.20.
2.20.
class SqEquation{
public static void main(String args[]){
// :
double a=2,b=-3,c=1;
// :
double x1,x2,D;
// :
System.out.println(" ax^2+bx+c=0. :");
System.out.println("a="+a+"\nb="+b+"\nc="+c);
// a 0:
if(a==0){System.out.println(" !");
// a 0 b 0:
if(b!=0){System.out.println(" x="+(-c/b)+".");}
// a, b, c :
else{if(c==0){System.out.println(" - .");}
// a b , c - :
else{System.out.println(" !");}
}
}
// a 0:
else{System.out.println(" !");
// ():
D=b*b-4*a*c;

72

2. Java

2.20 ()
// :
if(D<0){System.out.println(" !");}
// :
else{if(D==0){System.out.println(" x="+(-b/2/a));}
// :
else{x1=(-b-Math.sqrt(D))/2/a;
x2=(-b+Math.sqrt(D))/2/a;
System.out.println(" : x="+x1+" x="+x2+".");
}
}
}
// :
System.out.println(" !");}
}

, .
:
ax^2+bx+c=0. :
a=2.0
b=-3.0
c=1.0
!
: x=0.5 x=1.0.
!

,
:
ax^2+bx+c=0. :
a=1.0
b=-2.0
c=1.0
!
x=1.0
!

, :
ax^2+bx+c=0. :
a=2.0
b=-3.0
c=6.0
!
!
!

73

a , :
ax^2+bx+c=0. :
a=0.0
b=-3.0
c=6.0
!
x=2.0.
!

:
ax^2+bx+c=0. :
a=0.0
b=0.0
c=1.0
!
!
!

:
ax^2+bx+c=0. :
a=0.0
b=0.0
c=0.0
!
- .
!

, , .


, ,
, , ,
. , : ( ),
, ,
, , , .
V, , , m, H1 (
), H2 ( ), g, 1 2

74

2. Java

. Hmax, Smax
Tmax.
.
( ),
( ). , , mx = F x ( x , y )
= mg F y ( x , y ). , x y my
, F x ( x , y ) F y ( x , y )
, , ,
, y.
,
t .
. n- t n = nt
x n y n , Vn
U n . , n- (n+ 1)- . , :
x n +1 = x n + Vn t ,
y n +1 = y n + U n t ,
Vn +1 = Vn

F x ( x , y )
t ,
m

U n +1 = U n g t

F y ( x , y )
m

t .

, n = 0 , x 0 = 0 , y 0 = 0 , V0 = V cos()
U 0 = V sin() , V , , .
,
( , y < H 1 ) :
F x = 1Vn Vn2 + U n2 ,
F y = 1U n Vn2 + U n2 .
( H 1 y < H 2 ) F x = 2Vn

75

F y = 2U n . , (
H 2 y ) F x = 0 F y = 0 . . 2.21.
2.21.
class BodyFlight{
public static void main(String args[]){
// (/^2):
double g=9.8;
// ():
double m=0.1;
// (/):
double V=100;
// :
double alpha=60;
// ():
double H1=100,H2=300;
// (/ Hc^2/^2):
double gamma1=0.0001,gamma2=0.0001;
// ():
double dt=1E-6;
// ( /)
double Xn=0,Yn=0,Vn,Un;
// ():
double Fx,Fy;
// (), () ():
double Tmax,Smax,Hmax=0;
// ( ):
int height;
// :
alpha=Math.toRadians(alpha);
// :
Vn=V*Math.cos(alpha);
Un=V*Math.sin(alpha);
for(int n=1;true;n++){
// :
Yn+=Un*dt;
// :
if(Yn<0){
Tmax=Math.round((n-1)*dt*100)/100.0;
Smax=Math.round(Xn*100)/100.0;
Hmax=Math.round(Hmax*100)/100.0;
break;}
// :
Xn+=Vn*dt;

76

2. Java

2.21 ()
// :
if(Yn>Hmax) Hmax=Yn;
// :
height=Yn<H1?1:Yn<H2?2:3;
// :
switch(height){
// :
case 1:
Fx=gamma1*Vn*Math.sqrt(Vn*Vn+Un*Un);
Fy=gamma1*Un*Math.sqrt(Vn*Vn+Un*Un);
break;
// :
case 2:
Fx=gamma2*Vn;
Fy=gamma2*Un;
break;
// :
default:
Fx=0;
Fy=0;
}
// :
Vn+=-Fx*dt/m;
// :
Un+=-g*dt-Fy*dt/m;}
// :
System.out.println(" Tmax="+Tmax+" .");
System.out.println(" Smax="+Smax+" .");
System.out.println(" Hmax="+Hmax+" .");}
}

:
Tmax=15.97 .
Smax=705.95 .
Hmax=312.31 .

, ,
.2.1.
2.1.

g

()

alpha

77


H1

, .

H2

, .
( ) .

gamma1

gamma2

dt

. , . ,

Xn

. , .

Yn

. ,
. . ( ,
)

Vn

Un

Fx

Fy

height

,
,

Tmax

Hmax

Smax

, , . , , . ,
. ,
.

78

2. Java

, .
, . , ,
,

.
.
, .
,
true.

. .
. , break
. , Tmax
, . Xn ( Yn). Hmax.
: 100,
round(), 100.0 ( double, ).
Yn , .
,
Hmax. height=Yn<H1?1:Yn<H2?2:3 , . switch() . ,
, .

.

1.
. Java for(), while()
do-while(). Java: if() switch().
.

79

2. if() : if
(,
boolean). ( true), , .
, , else.
.
3. ( ) switch()
switch ,
. case .
case ,
. case
break.
default,
, , .
4. for() .
for .
. ( ) , .
. , .
.
, . . .
.
: ,
, , , ..
5. while() . , while.
( true),
( ). ..
, (
false), .
6. do-while() .
do
. while
. .
, while(),
,
, .

3.
, ?

, (), .
.
.
. Java !


. !

, , . ,
() .
. , , . , .
, , , ,
. :
[] =new [];

. , . , ,
new,

81

( ). , int nums=new int[20]


nums 20 .
,
: int[]nums nums
nums=new int[20]
nums. , :
int[] nums;
nums=new int[20];

,
. , int[] nums intnums[].

.
. ,
nums nums[0]. 20 , 19, nums[19].
length. ,
,
.
length, . , , ,
, length. , nums, nums.length. nums[nums.length-1],
.
, ++, Java, ++,
.
, .
. Java
, . .
.
.

( )
. :
int[] data={3,8,1,7};

82

3.

, .
data data[0]=3, data[1]=8, data[2]=1 data[3]=7. , :
int[] data;
data=new int[]{3,8,1,7};

int[] data . new


int[]{3,8,1,7} , data data=new int[]
{3,8,1,7}.
, 3.1.
3.1.
class MyArray{
public static void main(String[] args){
// :
int i,n;
// :
int[] data;
// :
data=new int[]{3,8,1,7};
// :
n=data.length;
// :
int[] nums=new int[n];
// :
for(i=0;i<n;i++){
nums[i]=2*data[i]-3;
System.out.println("nums["+i+"]="+nums[i]);}
}
}

data . , data.length, n ( n=data.length).


int[] nums=new int[n] nums. n, data. nums
. nums
data ( nums[i]=2*data[i]-3). System.out.println("nums["+i
+"]="+nums[i]).

83

:
nums[0]=3
nums[1]=13
nums[2]=-1
nums[3]=11

,
. i , (i<n)
.
, nums
n, . , Java .


, ?
. !

Java . . , .
Java
, .

, .
, ,
, (
,
). . :
[][] =new [_1][_2];

,
:
[][] ;
=new [_1][_2];

. _1 _2,

84

3.

. , double[][] data=new double[3][4]


data. double.
3, 4.
double[][] data;
data=new double[3][4];

: ,
. . , data[0][3] data 0 3.

, .
.
:
double data[][]={{0.1,0.2,0.3},{0.4,0.5,0.6}};
int nums[][]={{1,2,3},{4,5}};

data 2 3 ( 2, 3).
, data , ,
, . , data[0][0] 0.1, data[0][2] 0.3, data[1][0] 0.4, data[1][2] 0.6.
.
nums, -. 3, 2! , Java
,
. nums[0][0]
1, nums[0][1] 2, nums[0][2] 3,
nums[1][0] 4, nums[1][1] 5.
nums[1][2] !
3.2 ,
.
3.2.
class MyDArray{
public static void main(String[] args){
// :
int i,j,n=3;

85

// :
int[][] nums=new int[n-1][n];
// :
for(i=0;i<n-1;i++){
for(j=0;j<n;j++){
// :
nums[i][j]=10*(i+1)+j+1;
// :
System.out.print(nums[i][j]+" ");}
//
System.out.println();}
}
}

int[][] nums=new int[n-1][n] nums


n-1 n . n 3.
( nums[i][j]=10*(i+1)+j+1). . :
11 12 13
21 22 23

3.3 , .
3.3.
class ArrayDemo{
public static void main(String[] args){
// :
int i,j,n;
// ( ):
int[][] nums=new int[5][];
// :
n=nums.length;
// :
for(i=0;i<n;i++){
nums[i]=new int[i+1];}
// :
for(i=0;i<n;i++){
for(j=0;j<nums[i].length;j++){
// :
nums[i][j]=10*(i+1)+j+1;
// :
System.out.print(nums[i][j]+" ");}

86

3.

3.3 ()
// :
System.out.println();}
}
}

int[][]nums=newint[5][],
nums.
, .
! -
, n n=nums.length
. , .
nums.length nums, 5
.
i 0
n-1. nums[i]=new int[i+1] nums. , nums , nums[i] i- nums. new int[i+1]
, i+1,
nums[i]. : ,
.., .
. i 0 n-1
nums. j, nums, i.
nums[i] nums[i].length.
j 0 nums[i].length-1. nums[i][j]=10*(i+1)+j+1.
:
11
21
31
41
51

22
32 33
42 43 44
52 53 54 55

( ) . 3.4
, .
,
. 0, 1 2 . ,
, 1.

87

1. , 1, .
3.4.
class MyTArray{
public static void main(String[] args){
// :
int i,j,k;
// :
byte[][][] epsilon=new byte[3][3][3];
// :
for(i=0;i<3;i++)
for(j=0;j<3;j++)
for(k=0;k<3;k++)
epsilon[i][j][k]=0;
// :
epsilon[0][1][2]=epsilon[1][2][0]=epsilon[2][0][1]=1;
// -1:
epsilon[1][0][2]=epsilon[0][2][1]=epsilon[2][1][0]=-1;
}
}

epsilon byte[][][] epsilon=new


byte[3][3][3].
, . epsilon[0][1][2]=epsilon[1][2][0]=epsilon[2][0][1]=1
-1 ( epsilon[1][0][2]=epsilon[0][2][1]=epsilon[2][1][0]=-1).


?
? !

.

++ ,

. Java , , , . , Java
.

88

3.

char,
. 3.5 .
3.5.
class CharArray{
public static void main(String[] args){
char[] words=new char[]
{'','','','','','','','','','',' ','','','','','',''};
System.out.println(words);
}
}

: words
. System.out.println(words)
. , println()
( words). (
) . 8,
( String StringBuffer).

3.6.
3.6.
class CharArray2{
public static void main(String[] args){
char[] words=new char[]{'','','','',''};
char[] code=new char[words.length];
for(int i=0;i<words.length;i++)
code[i]=(char)(words[i]+i+1);
System.out.println(words);
System.out.println(code);
}
}

, words.
, .
code. words.
code .
code[i]=(char)(words[i]+i+1).
words[i]+i+1 words[i]
( ) i+1.

89

. code.
.
:

. .

,
, . . ,

. ,
, Java.
, Java.
, ( ), . , .
( )
. :
int[]nums;
nums=newint[]{1,2,3,4};

int[]nums , nums. . () - ,
.
new
, . new int[]{1,2,3,4}
,
.
( ). new . . -

90

3.

nums. ,
:
int[]nums,data;
nums=newint[]{1,2,3,4};
data=nums;

. int[]nums,data nums data. nums=new int[]{1,2,3,4}


, nums.
data=nums nums
data. nums .
data ! ,
data[1] , nums[1] ( 2). ,
. , - data (, data[3]=-1),
nums. ,
.
== != (, nums==data nums!=data) ,
. nums==data true, nums data
.
, ,
3.7.
3.7.
class MyArrayDemo{
public static void main(String[] args){
int i;
int[] nums=new int[10];
int[] data=new int[20];
for(i=0;i<10;i++){
nums[i]=2*i+1;
data[i]=2*i;
data[i+10]=2*(i+10);}
data=nums;
for(i=0;i<data.length;i++)
System.out.print(data[i]+" ");}
}

: nums 10 data 20 . : nums , data


. data=nums data
nums. ,

91

, . data (
print()). :
1 3 5 7 9 11 13 15 17 19

, nums.
, , data,
length data. 20, 10! . data=nums data
, nums.
() 3.8.
3.8.
class MyArrayDemo2{
public static void main(String[] args){
// :
int[] nums=new int[]{1,2,3,4,5};
int[] data=new int[]{1,2,3,4,5};
// :
// data=nums;
// :
if(data==nums){
System.out.println(" !");
return;}
// :
if(data.length!=nums.length){
System.out.println(" !");
return;}
// :
for(int i=0;i<data.length;i++){
if(data[i]!=nums[i]){
System.out.println(" !");
return;}}
System.out.println(" !");
}}

. nums data .
. .
nums data. , , ,
().

92

3.

if() data==nums.
!.
, return.
, . , . , .
if(), data.length!=nums.length.
, .
!, .
, . if() data[i]!=nums[i] (i ).
, !, .
, , , , ,
!.
, 3.8,
!. data=nums.
, !.
, , , .


,
. . , , () , .


. , ,

. , a b
, :
3

a b = a k bk .
k =1

93

a k bk ( k = 1, 2, 3 ) .

a b :

i j k


c = [a b ] = a1 a 2 a 3 = i (a 2 b3 a 3b2 ) + j (a 3 b1 a1b3 ) + k (a1b2 a 2 b1 ) .
b1 b2 b3


i , j k .
, .
.
. c k a k bk :
c k = a k +1bk + 2 a k + 2 bk +1 .
: , . ,
1 3, a 4 a1 a 5 a 2.
0 2, 3 0, 4 1.
3.9 ,
.
3.9.
class VectProduct{
public static void main(String args[]){
// :
double[] a,b,c;
// :
a=new double[]{1,2,-1};
b=new double[]{3,-1,2};
c=new double[3];
// :
int k;
// :
double s=0;
System.out.print(" :\n[a.b]=<");
// :
for(k=0;k<3;k++){
s+=a[k]*b[k];
c[k]=a[(k+1)%3]*b[(k+2)%3]-a[(k+2)%3]*b[(k+1)%3];

94

3.

3.9 ()
System.out.print(c[k]+(k!=2?";":">\n"));}
System.out.println("a.b="+s);}
}

double[] a,b,c .
a=new double[]{1,2,-1} b=new double[]{3,-1,2} . c=new double[3] . .
k , s
double, .
. s+=a[k]*b[k] , ,
, c[k]=a[(k+1)%3]*b[(k+2)%3]-a[(k+2)%3]*b[(k+1)%3]
- . , 3
, .
System.out.print(" :\
n[a.b]=<")
. print()
\n , .
System.out.
print(c[k]+(k!=2?";":">\n")). print()
, . 2 (
), . ( 2),
. ,
2. ,
,
.
System.out.println
("a. b="+s) .
:
:
[a.b]=<3.0;-5.0;-7.0>
a.b=-1.0

95

, , ,
.


,
. ,
. 3.10.
3.10.
class FibonacciArray{
public static void main(String args[]){
// :
int k,n=20;
// :
int[] Fib=new int[n];
// :
Fib[0]=1;
Fib[1]=1;
// :
System.out.print(Fib[0]+" "+Fib[1]);
// :
for(k=2;k<n;k++){
// :
Fib[k]=Fib[k-1]+Fib[k-2];
// :
System.out.print(" "+Fib[k]);}}
}

:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

, , . , , .
( ).
.
( ). ,
, .
,
.

96

3.



. , n :
Pn ( x) =

a k x k.

k =0

x,
.
a k , k = 0,1, ..., n . , x, a k .
,
. :
Pn ( x) =

n 1

(k + 1)a k +1 x k.

k =0

n 1 , - . bk = (k + 1)a k +1 k = 0,1, ..., n 1 bn = 0 . 3.11


,
.
3.11.
class Polynom{
public static void main(String args[]){
// :
double[] a=new double[]{1,-3,2,4,1,-1};
// :
double[] b=new double[a.length-1];
// :
double x=2.0,q=1;
// :
int k;
// :
double P=0,Q=0;
// :
for(k=0;k<b.length;k++){
// :
P+=a[k]*q;
// :
b[k]=(k+1)*a[k+1];

97

// :
Q+=b[k]*q;
// :
q*=x;}
// :
P+=a[a.length-1]*q;
// :
System.out.println(" P(x)="+P);
System.out.println(" P'(x)="+Q);}
}

double[]a=newdouble[]{1,-3,2,4,1,-1} , .
double[] b=new double[a.length-1] -.
. , , . a.length.
x double , q ,
. 1. k , P Q
double
.
k 0 b.length-1, b
-. .
P+=a[k]*q . a[k],
.
q, , , . b[k]=(k+1)*a[k+1] -. Q+=b[k]*q,
-, , , q. ,
q*=x (
).
,
. P+=a[a.length-1]*q .
q, .

98

3.


:
P(x)=19.0
P'(x)=5.0

, .


. , , . . , .
,
.
. ..
. ,
,
.
3.12 , .
3.12.
class Bubble{
public static void main(String args[]){
// :
int m,k,s,n=15;
// :
int[] nums=new int[n];
System.out.println(" :");
// :
for(k=0;k<n;k++){
// - :
nums[k]=(int)(5*n*Math.random());
System.out.print(nums[k]+" ");}
// :
for(m=1;m<n;m++){
for(k=0;k<n-m;k++){
if(nums[k]>nums[k+1]){
s=nums[k];
nums[k]=nums[k+1];
nums[k+1]=s;}
}}

99

// :
System.out.println("\n :");
for(k=0;k<n;k++){
System.out.print(nums[k]+" ");}
}}

nums,
. Math.random(),
0 1.
5 ( n), (int)
.
. .
. m . ,
, .
, , .
.
k . 0 n-m-1. , -, ,
k k k+1,
, k. -, -
, .
,
. :
:
63 18 5 30 70 13 21 42 47 38 52 43 51 44 34
:
5 13 18 21 30 34 38 42 43 44 47 51 52 63 70

, ( ) . .



.
, . .

100

3.

A n a ij ,
+
i, j = 1, 2, ..., n, A
a ij+ = a ji . , , .
3.13 , .
3.13.
class MatrTrans{
public static void main(String args[]){
// :
int n=4;
// :
int[][] A=new int[n][n];
// "" :
int i,j,tmp;
System.out.println(" :");
// :
for(i=0;i<n;i++){
for(j=0;j<n;j++){
A[i][j]=(int)(10*Math.random());
System.out.print(A[i][j]+(j!=n-1?" ":"\n"));}}
// :
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
tmp=A[i][j];
A[i][j]=A[j][i];
A[j][i]=tmp;}}
// :
System.out.println(" :");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.print(A[i][j]+(j!=n-1?" ":"\n"));}}
}}

:
:
0 8 6 5
8 2 2 4
6 2 0 3
8 1 9 0
:
0 8 6 8
8 2 2 1
6 2 0 9
5 4 3 0

101

int[][] A=new int[n][n] A, . ()


. ,
, (int)(10*Math.random()).
0 9 .
System.out.print(A[i][j]+(j!=n-1?" ":"\n")). print() , . ,
n-1 (
). . , .
.
.
, ,
. i,
, 0 n-1, , , i+1 n-1.
, ,
( ).

.


A B n a ij bij ( i, j = 1, 2, ..., n ), C = AB :
n

c ij = a ik bkj .
k =1

3.14 , .
3.14.
class MatrProd{
public static void main(String args[]){
// :
int n=4;
// :
int[][] A,B,C;
A=new int[n][n];

102

3.

3.14 ()
B=new int[n][n];
C=new int[n][n];
// :
int i,j,k;
// :
System.out.println(" A:");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
A[i][j]=(int)(20*Math.random()-9);
System.out.print(A[i][j]+(j!=n-1?"\t":"\n"));}}
// :
System.out.println(" B:");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
B[i][j]=(int)(20*Math.random()-9);
System.out.print(B[i][j]+(j!=n-1?"\t":"\n"));}}
// - :
System.out.println(" C=AB:");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
for(k=0;k<n;k++){
C[i][j]+=A[i][k]*B[k][j];}
System.out.print(C[i][j]+(j!=n-1?"\t":"\n"));}}
}}

:
A:
4
-2
8
-2
2
-1
4
-8
7
0
1
-5
-5
2
0
-3
B:
9
-6
-4
-6
-6
8
0
7
-1
7
3
-8
0
-6
0
-1
C=AB:
40
28
8
-100
20
56
4
-43
62
-5
-25 -45
-57 64
20
47

. . . Java, ,

103

. \t , .



. . . ,
, . - ,
. , ,
, .
.
( ), , .
. : 0
, 1 . . , 0 1.
p, 1.
0. , p
, .
.
, , 2.
, 0, 2.
, .
. 2 (
), , 0
( ), 2.
..,
.
, , .
2, .
,
. . , , ,
( p).
: p

104

3.

( )
, , .
, 3.15 p ( ), . .
.
3.15.
class Percolation{
public static void main(String args[]){
// :
int N=100;
// :
int M=5;
// :
int n=200;
// -:
int count;
// :
double q=0.57,dq=0.01;
// :
int[][] A=new int[n][n];
// :
double[][] P=new double[2][M+1];
// :
int i,j,k,m;
// :
for(m=0;m<=M;m++) P[0][m]=q+dq*m;
// :
for(m=0;m<=M;m++){
// :
P[1][m]=0;
for(k=1;k<=N;k++){
for(i=0;i<n;i++){
for(j=0;j<n;j++){
// :
if(Math.random()>P[0][m]) A[i][j]=1;
else A[i][j]=0;}}
// "" ( ):
for(i=0;i<n;i++){
if(A[i][0]==0) A[i][0]=2;}

105

// :
do{
// :
count=0;
// :
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(A[i][j]==2){
if(i>0&&A[i-1][j]==0) {A[i-1][j]=2; count++;}
if(i<n-1&&A[i+1][j]==0) {A[i+1][j]=2; count++;}
if(j<n-1&&A[i][j+1]==0) {A[i][j+1]=2; count++;}
if(j>0&&A[i][j-1]==0) {A[i][j-1]=2; count++;}
}}}
}while(count>0);
// :
for(i=0;i<n;i++){
if(A[i][n-1]==2){
P[1][m]+=(double)1/N;
break;}
}}}
// :
System.out.print(" \t");
for(m=0;m<=M;m++){
System.out.print(Math.round(P[0][m]*100)/100.0+(m!=M?"\t":"\n"));}
System.out.print(" \t");
for(m=0;m<=M;m++){
System.out.print(Math.round(P[1][m]*100)/100.0+(m!=M?"\t":"\n"));}
}}

, , .3.1.
3.1.

, ,

. ,

, (M+1)
,

,
, , A,

106

3.

3.1 ()

count

-. A,
2.
, count ,
A. count .
count , A ..
,
count ( )

. (, (M+1)- )
. q, q+M*dq

dq

, . () A 0
( ) 1 ( ). , 0,
2. ,

2 M+1 double.
P[0]
, . P[1] , P[0]

,
P[0][m]=q+dq*m ( m
0 M ) P[0] P
,
.
( m
) P[1].
P[1][m]=0 ( ,

107

). (
k 1 N ),

.
. ,
,
A . .
A ,
0, 2 , . . , do-while().
- count ,
count>0. do-while() A. 2,
, , 2. , . ,
, .
A. , ,
, 0, ,
. ,
&&. ,
, false,
. ,
.
A 2, count . , do-while() , A
.
.
, , ,
, , , A
2. .
2 , P[1][m] 1/N,
( break).
, . . , :
0.57 0.58 0.59 0.6 0.61 0.62
0.0 0.07 0.4 0.78 0.95 1.0

108

3.

, , . , ,
, .

1. ,
( ). Java

.
2. . -, ,
. -, new
. ( ) .
3.
. . new

.
4. ( ).
( ) .
( ).
(
new).
( ).
5. : . .
.
6. Java
. ( ) length (
).

109

7. .

,
. . , .
8. print() println()
(, ),
.

4.
, , !
!

Java . , Java , ,
, .
Java ( ). , ,
.


,
!

Java -.
, , Java, - ().
, . , , , Java.
, , ,
. ,
, ,
, . ,

111

,
. . ,

. -, ,
, . . , , - .
-
, . , , , , : ,
. , .
.


, .
, , .

. , .
, . ,
, . , , . ,
, ,
.
, ( ), , .

(),
.
, .
, .
, . () .
( ) ().
( ), . ,
. ,

112

4.

( ). , .
, . , ,

. ,
. . , ,
, , , . , ,
, ,
- . , . ,
, .
, : (
), ( ), ( ), ( ) ( ). .
: ,
, .
. . ,
, ,
, . -.
, , , , ,
. , -
, ,
.

,

, .
. . .
, ,
. -
,
.

. , . . ,
.

113

, , , , .
.
. ,
, ,
. . ,
().
(, ).
.
. ,

. ,
, .
.
, . ,
, ,
. , ,
,
,
.

, . ,
.


. .

. .
- ,
,
.

114

4.

- ,
.
- . .
, , , .
.


?! ?!

Java.
class.
. : .
( ). , :
class _{
//
}


( ). ,
, . ,
, ,
, .
. ,
, ,
,
. ,
.
,
. Java
() ().
,
void. :
_ _(){
//
}

115

, , return. , return , ,
.
, return
, .
, (, ), .
, , . ,
. main(). , main(), .
( ). (, ).
, , ,
, , main(). , .
.
.
, .
,
. .
( )
.
,
, . ( )
new, .
,
, ,
. ,
:
_ _; //
_=new _(); //

:
_ _=new _();

116

4.

, :
class MyClass{
double x;
int m;
void set(double z, int n){
x=z;
m=n;}
}

MyClass ( x double m
int), set(). ,

void. : double
int. x, m.
, .
, , , .
MyClass :
MyClass obj; //
obj=new MyClass(); //

:
MyClass obj=new MyClass();

:
.
, Java- .
, .
, ++. , Java
.
, ,
. , - ,

. Java, - ,
.
,
, . , ,
( ).
.

117

.
, (
). .
4.1 ; , ,
, ,
, .
4.1.
class Coords{
// :
double x;
double y;
double z;
// :
void set(double a,double b,double c){
x=a;
y=b;
z=c;
}
// :
double getDistance(){
return Math.sqrt(x*x+y*y+z*z);}
}
class CoordsDemo{
public static void main(String[] args){
// :
Coords obj=new Coords();
// :
obj.set(5.0,0,2.5);
// :
obj.y=-4.3;
// :
System.out.println(" : "+obj.getDistance());
}
}

Coords, x, y z
double. . , . set() ( void)
. , x,
y z .
getDistance()
double,

118

4.

(, x, y z
x 2 + y 2 + z 2 ). sqrt() Java- Math.
,
Math.sqrt().
main() CoordsDemo Coords obj=new Coords()
obj Coords. obj.set(5.0,0,2.5) set(), .
obj.y=-4.3 y . ,
getDistance() obj.getDistance() println(). , . :
: 7.052659073002181

. Java
.
.class,
. ,
, , main().


- , ?
, !

, , . , . ,
, . , .
++, . ,
.
, , static. :
static _ _;

static
(. ).

119

. static,
. . :
static{ //
//
}
//


( ), , ,
: .
,
. : , , , , , ,
,
. , this ( , )
super ( , ). , .
, . ,
static:
static _ _( ){
//
}

, ,
_._. 4.2
.
4.2.
class UsingStatic{
// :
static int a=3;
static int b;
// :
static void meth(int x){
System.out.println("x="+x);
System.out.println("a="+a);
System.out.println("b="+b);}
// :
static{
System.out.println(" :");
b=a*4;}

120

4.

4.2 ()
// :
public static void main(String args[]){
meth(123);
}}

UsingStatic a b int meth(). a 3.


b . b=a*4,
.
meth() . .
.
UsingStatic main(),
meth() 123. ,
, , .
:
:
x=123
a=3
b=12


, meth() b .
4.3.
4.3.
class MyStatic{
// :
static int a=50;
static int b=120;
// :
static void callme(){
System.out.println("a="+a);
}}
// :
class StaticDemo{
public static void main(String args[]){
// :
MyStatic.callme();
// :
MyStatic obj1=new MyStatic();
MyStatic obj2=new MyStatic();

121

// :
obj1.a=-25;
// :
System.out.println("a="+obj2.a);
// :
System.out.println("b="+MyStatic.b);
}}

:
a=50
a=-25
b=120

. MyStatic
a b 50 120 . , callme().
,
a. StaticDemo
obj1 obj2 MyStatic. MyStatic.callme() callme(). ,
,
. obj1.a=-25 a .
obj1,
, . , System.out.println("a="+obj2.a). ,

System.out.println("b="+MyStatic.b).
. ,
. ,
.
( ).
,
().

/ -66

,
, .

122

4.

,
, .
Java
: , .
, ,
. ,
, . - ,
, (, .
.).
,
.
. , .
, .
. , ,
.
,
.
, .
.
: public,
private protected ,
. . Java
++: ++ .
,
. , . , ++: .
4.4
.
4.4.
class MyClass{
// :
private int a;
private int b;
// :
private void showab(){
// :
System.out.println("a="+a);

123

System.out.println("b="+b);}
// :
public void setab(int x,int y){
// :
a=x;
b=y;
System.out.println(" !");}
// :
void getab(){
System.out.println(" :");
// :
showab();}
}
class PrivateDemo{
public static void main(String[] args){
// :
MyClass obj=new MyClass();
// :
obj.setab(3,5);
obj.getab();
}}

MyClass a b.
, . setab().
, a b. , setab()
, , , . setab()
public. getab() ,
( ). showab(),
a b.
PrivateDemo obj
MyClass. obj.setab(3,5) obj 3 5 . obj.getab()
. :
!
:
a=3
b=5

, main() , , obj.a, obj.b obj.showab(),


MyClass (private).
:

124

4.

.
, . , ,
. ,
.
, (). . ,
. , . ,
. . ,
,
.

this
!
?!

. .

this , . , Java .
, .
,
this: .
, .
this
.

.
, .
, , . ,
.

this. 4.5.

this

125

4.5. this
class MyClass{
// :
double Re,Im;
void set(double Re,double Im){
// this:
this.Re=Re;
this.Im=Im;}
void get(){
// \n:
System.out.println(" :\nRe="+this.Re+" Im="+this.Im);}
}
class ThisDemo{
public static void main(String[] args){
MyClass obj=new MyClass();
obj.set(1,5);
obj.get();}
}

MyClass Re Im double. , , ,
, . ,
( Re) ( Im) .
, : set()
get() . set()
double,
. , ,
, , . set() Re Im,
, ,
( , ).
, this. , this.Re
this.Im Re Im this,
, set(). Re Im . , , this.
Re=Re : Re this (, set()) Re, ,
set() . this, ,
.

126

4.

this get(),
. this.Re this.Im
Re Im
. , . , ( )
this (
this). Java .
this
.
\n println() get(). ,

.
:
:
Re=1.0 Im=5.0

, this. .


, !

/ -66

, .
. , , . , , . ,
,
, , .
. -,
( ). -,
. ,
. 4.6.

127

4.6.
class MyOuter{
// :
int number=123;
// :
void show(){
// :
MyInner InnerObj=new MyInner();
// :
InnerObj.display();}
// :
class MyInner{
// :
void display(){
System.out.println(" number="+number);}
}
}
class InnerDemo{
public static void main(String args[]){
// :
MyOuter OuterObj=new MyOuter();
// :
OuterObj.show();}
}

: MyOuter, MyInner, InnerDemo. InnerDemo


main(), MyOuter
show().
: MyOuter
number, show() MyInner.
display(),
show(). display() show() InnerObj. , display()
.
display()
number. , number
.
:
number=123

,
,
.

128

4.


, !

. .

, new . ,
. . , , ,
, .
, .

, . 4.7.
4.7.
class MyClass{
void show(String msg){
System.out.println(msg);}
}
class NamelessDemo{
public static void main(String args[]){
// :
new MyClass().show(" ");}
}

MyClass show() . Java- String.


, , .
main() NamelessDemo , :
new MyClass().show(" ")

. new MyClass()
MyClass,
. , . MyClass,
show(). " ".
new MyClass() .
.
.

129


,
(, main())
.


,
. ,
: p
n . q = 1 p
.
( ), . M = np , D = npq . ,

. .
4.8 , .
4.8.
class Bernoulli{
// () :
private int n;
// :
private double p;
// :
private boolean[] test;
// :
public void setAll(int n,double p){
if(n>=0) this.n=n;
else n=0;
if(p>=0&&p<=1) this.p=p;
else this.p=0;
test=new boolean[n];
for(int i=0;i<n;i++){
if(Math.random()<=p) test[i]=true;
else test[i]=false;}
}
// :
private int getVal(){

130

4.

4.8 ()
int count,i;
for(i=0,count=0;i<n;i++) if(test[i]) count++;
return count;}
// :
public void show(){
System.out.println(" ");
System.out.println(": "+n);
System.out.println(" : "+p);
System.out.println(": "+getVal());
System.out.println(": "+(n-getVal()));
System.out.println(". : "+n*p);
System.out.println(". : "+Math.sqrt(n*p*(1-p)));}
}
class BernoulliTest{
public static void main(String args[]){
// :
Bernoulli obj=new Bernoulli();
// :
obj.setAll(10000,0.36);
// :
obj.show();
}}

Bernoulli . n . p double
. ,
, .
,
. test.
boolean ( true , false).
. n. p.
,
test: p test,
n . setAll(), :
n, double p. ,
.
,
. ,
.

131

n p , test=new boolean[n]
,
test. Java , , , ,
, Java. .
Math.random(), 0 1. :
p, true,
false. Math.random() 0 1, test true
p false 1-p, .
getVal()
. test.
count. test, true, count . count
.
getVal() show().
show() . , ,
,
, ,
.
Bernoulli obj=new Bernoulli()
obj Bernoulli. obj.setAll(10000,0.36)
, obj.show() .
:

: 10000
: 0.36
: 3667
: 6333
. : 3600.0
. : 48.0

,
Bernoulli setAll().
.


Java ,
,

132

4.

. 4.9.
4.9.
// :
class MyMath{
// :
static double L=Math.PI;
// :
static double Exp(double x,int N){
int i;
double s=0,q=1;
for(i=0;i<N;i++){
s+=q;
q*=x/(i+1);}
return s+q;}
// :
static double Sin(double x,int N){
int i;
double s=0,q=x;
for(i=0;i<N;i++){
s+=q;
q*=(-1)*x*x/(2*i+2)/(2*i+3);}
return s+q;}
// :
static double Cos(double x,int N){
int i;
double s=0,q=1;
for(i=0;i<N;i++){
s+=q;
q*=(-1)*x*x/(2*i+1)/(2*i+2);}
return s+q;}
// :
static double BesselJ(double x,int N){
int i;
double s=0,q=1;
for(i=0;i<N;i++){
s+=q;
q*=(-1)*x*x/4/(i+1)/(i+1);}
return s+q;}
// :
static double FourSin(double x,double[] a){
int i,N=a.length;
double s=0;
for(i=0;i<N;i++){
s+=a[i]*Math.sin(Math.PI*x*(i+1)/L);}

133

return s;}
// :
static double FourCos(double x,double[] a){
int i,N=a.length;
double s=0;
for(i=0;i<N;i++){
s+=a[i]*Math.cos(Math.PI*x*i/L);}
return s;}
}
class MathDemo{
public static void main(String args[]){
System.out.println(" :");
// :
System.out.println("exp(1)="+MyMath.Exp(1,30));
// :
System.out.println("sin(pi)="+MyMath.Sin(Math.PI,100));
// :
System.out.println("cos(pi/2)="+MyMath.Cos(Math.PI/2,100));
// :
System.out.println("J0(mu1)="+MyMath.BesselJ(2.404825558,100));
// y(x)=x:
int m=1000;
double[] a=new double[m];
double[] b=new double[m+1];
b[0]=MyMath.L/2;
for(int i=1;i<=m;i++){
a[i-1]=(2*(i%2)-1)*2*MyMath.L/Math.PI/i;
b[i]=-4*(i%2)*MyMath.L/Math.pow(Math.PI*i,2);}
// y(x)=x - :
System.out.println("2.0->"+MyMath.FourSin(2.0,a));
// y(x)=x - :
System.out.println("2.0->"+MyMath.FourCos(2.0,b));
}}

MyMath, . , ,
, .
.
: double , ,
. :
exp( x)

xk
.
k =0 k !
N

134

4.

:
sin( x)

(1) k x 2k +1
,
k =0 (2k + 1)!
N

sin( x)

(1) k x 2k
(2k)! .
k =0
N

J 0 ( x)

x
(1) k
2

2k

(k !)2

k =0

, MyMath nx
nx
sin
( FourSin()) cos L
L

( FourCos()). , FourSin() :
x double, a double. :
N

nx
.
L

a n1 sin

n =1

an a, N ( N=a.length),
(,
) 0 L
, a. L MyMath
Math.PI.
, y( x) 0 L :
y( x ) =

nx
.
L

y n sin

n =1

:
L

yn =

2
nx
y( x) sin
dx .
L 0
L

y( x) 0 < x < L . ,
y( x) 0 L :

nx
y( x) = y 0 + y n cos
.
L
n =1

135

:
L

yn =

2
1
nx
y( x) cos
dx n> 0 y 0 = y( x)dx n= 0.

L0
L0
L

y( x) 0 < x < L. ,
.
. , ,
(, ).
MathDemo MyMath . , :
:
exp(1)=2.7182818284590455
sin(pi)=2.4790606536130346E-16
cos(pi/2)=4.590388303752165E-17
J0(mu1)=-1.5793881580131606E-10
2.0->1.9996438367829905
2.0->1.999999349096476

, e 2, 7182818284590452 (
).
Math.PI,

Math.PI/2. , .
( ).
1 2.404825558 . , n
( n = 1, 2, ... ) J 0 ( x) J 0 ( n ) = 0. ( )
.
, FourSin() FourCos()
y( x) = x x = 2. a b y( x) = x
.
. ,

136

4.

2L
, n
n
L
2L((1) 1)
y n =
n > 0 y 0 = .
2 2
2
n
a b .
MyMath.FourSin(2.0,a) MyMath.FourCos(2.0,b)
y( x) = x x = 2 , 2.
( a b),
.
- y n = (1) n +1


.
, , , .
, ,
, , . 4.10.
4.10.
class MyClass{
// :
int number=0;
// ;
MyClass next=this;
void create(int n){
int i;
MyClass objA=this;
MyClass objB;
// :
for(i=1;i<=n;i++){
objB=new MyClass();
objA.next=objB;
objB.number=objA.number+1;
objA=objB;}
// :
objA.next=this;
}
// :
int getNumber(int k){
int i;
MyClass obj=this;
for(i=1;i<=k;i++) obj=obj.next;
return obj.number;}
}

137

class ObjList{
public static void main(String[] args){
// :
MyClass obj=new MyClass();
// 4- ( + 3 ):
obj.create(3);
// :
System.out.println(" number :");
System.out.println("2- -> "+obj.getNumber(2));
System.out.println("4- -> "+obj.getNumber(4));
System.out.println("2- 1- -> "+obj.next.getNumber(2));
}}

MyClass, :
number next
MyClass. . this,
, .
create(). ,
, .
i, objA ( ) MyClass
this , create(), objB ( ) MyClass.
,
1 n ( create()) . objB=new MyClass() MyClass,
objB.
objA.next=objB next objA objB.
next
. objB.number=objA.number+1 number ,
number . , objA=objB
objA . objB. objA objB . number
( ).
next (
- ).
objA.next=this. this
, create(), . .
getNumber()
number ,

138

4.

. ( ), getNumber()
, . : ,
obj=obj.next (,
- next). obj
. number .
ObjList MyClass obj=new MyClass()
. obj.create(3)
( ). number 0,
number 1, 2 3.
. :
number :
2- -> 2
4- -> 0
2- 1- -> 3

, obj.getNumber(2) number , , 2. obj.getNumber(4) number ,


4 . 3
. . obj.getNumber(4) number
, 0. , obj.next.getNumber(2)
number , , next obj ( ).
.
3.


4.11 ,
. , (), , ()
, ,
.
4.11.
class SMatrix{
// :
private int n;

139

// :
private int[][] Matrix;
// :
void setBase(int n){
this.n=n;
Matrix=new int[n][n];}
// :
void setRND(){
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
Matrix[i][j]=(int)(Math.random()*10);
}
// :
void setVal(int a){
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
Matrix[i][j]=a;
}
// :
void setNums(){
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
Matrix[i][j]=(i*n+j)%9+1;
}
// :
void setE(){
int i;
setVal(0);
for(i=0;i<n;i++)
Matrix[i][i]=1;
}
// :
void show(){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.print(Matrix[i][j]+(j==n-1?"\n":" "));}
}
}
// :
int Sp(){
int i,s=0;
for(i=0;i<n;i++) s+=Matrix[i][i];

140

4.

4.11 ()
return s;}
// :
int det(){
int D=0;
switch(n){
// 1 1:
case 1:
D=Matrix[0][0];
break;
// 2 2:
case 2:
D=Matrix[0][0]*Matrix[1][1]-Matrix[0][1]*Matrix[1][0];
break;
case 3:
// 3 3:
int i,j,A,B;
for(j=0;j<n;j++){
A=1;
B=1;
for(i=0;i<n;i++){
A*=Matrix[i][(j+i)%n];
B*=Matrix[n-i-1][(j+i)%n];}
D+=A-B;}
break;
// :
default:
int k,sign=1;
SMatrix m;
for(k=0;k<n;k++){
m=new SMatrix();
m.setBase(n-1);
for(i=1;i<n;i++){
for(j=0;j<k;j++) m.Matrix[i-1][j]=Matrix[i][j];
for(j=k+1;j<n;j++) m.Matrix[i-1][j-1]=Matrix[i][j];
}
D+=sign*Matrix[0][k]*m.det();
sign*=(-1);
}
}
return D;}
// :
void trans(){
int i,j,s;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++){
s=Matrix[i][j];

141

Matrix[i][j]=Matrix[j][i];
Matrix[j][i]=s;}
}
}
class MatrixDemo{
public static void main(String[] args){
// :
SMatrix obj=new SMatrix();
// :
obj.setBase(3);
// :
obj.setRND();
// :
//obj.setE();
// :
//obj.setVal(1);
// :
//obj.setNums();
System.out.println(" :");
obj.show();
System.out.println(" :");
// :
obj.trans();
obj.show();
// :
System.out.println(" : "+obj.Sp());
// :
System.out.println(" : "+obj.det());
}}

SMatrix.
, ( Matrix)
. , .
n , , ,
. n , Matrix, , , .
.

. , setRND()
. Math.random(). ,
. (int)(Math.
random()*10) random()

142

4.

10, (
).
setNums() , 1 9, 1 ..
Matrix Matrix[i]
[j]=(i*n+j)%9+1.
setVal() .
Matrix . setE(). Matrix :
, .
:
( setVal() ),
. , ,
Java .
( ,
Matrix) setBase(). , Matrix .
n, this.n=n
this. Matrix=new int[n][n] ,
Matrix. ,
setBase() Matrix .
show() ,
Matrix .
. System.out.print(Matrix[i]
[j]+(j==n-1?"\n":"")) print() ,

, n-1, .
Sp() , .
( ).
trans() .
, Matrix.
Matrix, ( ).
,
( ).

143

det()
, Matrix.
switch() n
, . :
n 1, 2, 3 . D .
n 1, , , .
.
D Matrix[0][0] Matrix.
2, D=Matrix[0][0]*Matrix[1][1]-Matrix[0][1]*Matrix[1][0].
, A 2 2 a ij
( i, j = 1, 2 ) det( A) = a11a 22 a12 a 21 ,
.
3 3 ,

: , . , 4 1,
5 2 ..

3 3 switch() , n 3.
j. A B , ()
( i) :
A , , B , .
.
. , (
). , .
,
, (),
.
A*=Matrix[i][(j+i)%n] B*=Matrix[n-i-1][(j+i)%n].
D D+=A-B , A B.
3.
. ,
A n i, j = 1, 2, ..., n ,

144

4.

:
n

det( A) = (1) i + j a ij det(M ( ij ) ) .


j =1

M ( ij ) A i- j-
. M ( ij ) n 1 . , n
n n 1 .

M ( ij ) n 2 . .
3.
default switch().
,
i 1. Matrix .
default k sign 1. sign ( 1 1),
( ). m SMatrix. (),
. default . k 0 n-1. m=new SMatrix()
SMatrix, m. m.setBase(n-1)
, ,
. . m (
m.Matrix) Matrix,
k (
).
i 1 n-1 Matrix ( this.Matrix),
m.Matrix.
: 1 Matrix
0 m.Matrix, 2 Matrix 1 m.Matrix . .
, k- : j-
Matrix j- m.Matrix. ,
k- Matrix , (k+1)-
j- Matrix (j-1)-

145

m.Matrix. ( i)
: j 0
k-1, k+1 n-1.
m.Matrix D+=sign*Matrix[0][k]*m.det() D. ,
det(), m, .
, det() ,
. , . ,
sign*=(-1)
sign.
MatrixDemo SMatrix obj=new
SMatrix() SMatrix. - obj.setBase(3) (- 3). obj ,
obj.setRND(). , -
obj , .
obj.show() . obj.trans(),
obj.show()
. obj.Sp(),
obj.det(). . :
:
3 0 5
8 3 3
9 8 4
:
3 8 9
0 3 8
5 3 4
: 10
: 149

obj.setBase(5),
setNums(), :
:
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7

146

4.

:
1 6 2 7 3
2 7 3 8 4
3 8 4 9 5
4 9 5 1 6
5 1 6 2 7
: 20
: 0


, , . , (
). x y
( t ), :
d 2x
dt 2
d 2y
dt 2

= Fx m ;
= Fy m .

m , F x F y . F x = V x F y = mg V y , g
dx
, , V x =
dt
dy
V y =
.
dt

. , - x
y, , V x
V y. ,
dt ( ,
), x V x dt, y V y dt. F x dt m F y dt m V x V y .
(
t dt , dt
t n dt = t n),
t .
,
4.12.

147

4.12.
class BodyFlight{
// :
private final static double g=9.8;
// :
private final static double gamma=0.005;
// :
private final static int n=1000;
// :
private double t;
// :
private Body body;
// :
private void calculate(){
// , :
double x,y,dx,dy,Vx,Vy,dVx,dVy,dt;
// :
int i;
// :
Force F=new Force();
// :
x=body.x;
y=body.y;
Vx=body.Vx;
Vy=body.Vy;
// :
dt=t/n;
// :
for(i=1;i<=n;i++){
dx=Vx*dt;
dy=Vy*dt;
dVx=F.x(body)*dt/body.m;
dVy=F.y(body)*dt/body.m;
x+=dx;
y+=dy;
Vx+=dVx;
Vy+=dVy;
body.set(x,y,Vx,Vy);}
}
// :
BodyFlight(double[] params){
// ( ):
double m=params[0]/1000;
// :
double x=params[1];
double y=params[2];

148
4.12 ()
// :
double alpha=Math.toRadians(params[4]);
// :
double Vx=params[3]*Math.cos(alpha);
double Vy=params[3]*Math.sin(alpha);
// "":
body=new Body(m,x,y,Vx,Vy);
// :
this.t=params[5];
// t:
calculate();
// :
body.show();
}
// "":
class Body{
// :
double m;
// :
double x;
double y;
// :
double Vx;
double Vy;
// :
double V(){
return Math.sqrt(Vx*Vx+Vy*Vy);}
// :
double phi(){
return Math.atan2(Vy,Vx);}
// :
Body(double m,double x,double y,double Vx,double Vy){
this.m=m;
set(x,y,Vx,Vy);
}
//
// ( ):
void set(double x,double y,double Vx,double Vy){
this.x=x;
this.y=y;
this.Vx=Vx;
this.Vy=Vy;}
// :
void show(){

4.

149

double alpha=Math.round(Math.toDegrees(phi())*100)/100.0;
System.out.println(" t="+t+" .");
System.out.println(": "+Math.round(y*100)/100.0+" .");
System.out.println(" : "+Math.round(x*100)/100.0+"
.");
System.out.println(": "+Math.round(V()*100)/100.0+" .");
System.out.println(" : "+alpha+" .");}
}
// "":
class Force{
// :
double x(Body obj){
return -gamma*obj.Vx;}
// :
double y(Body obj){
return -g*obj.m-gamma*obj.Vy;}
}}
class BodyFlightDemo{
public static void main(String[] args){
// ( ( ), ( ),
// ( /)), ( ) ( )):
double[] params={100,0,0,150,30,5};
// :
new BodyFlight(params);
}}


BodyFlight, : Body
Force .
Body double: m,
x y, Vx Vy. V() (
V = V x2 + V y2 ). phi() ,
. atan2(), ( ) , (
, ). set() ,
( ).
, , .
.
show() Body
, , .

150

4.

, . .
Force x() y()
. ,
, .
, BodyFlight :
g ( ), gamma ( ), n ( ) final ( ) static (). t
, .
body Body.
, . calculate()
, BodyFlight
.
. , ,
Force,
.
BodyFlight
. :
( ), ( ), ( ), , ( ),
( ), . ,
,
1000.
Math.toRadians(), ( )
Math.toDegrees(). V ( ) V x = V cos()
V y = V sin() .
:
t=5.0 .
: 219.03 .
: 574.76 .
: 102.28 .
: 8.46 .

, , params
,
BodyFlight. ,
, .

151

1. - : , .
,
. .
( ) .
, . , ,
.
() .
2. class,
.
() (), .
. , ,
.
3. , . ,
.
: ,
, . static. ,
: public ( ), private ( ) protected ( ).
, .
4. Java ( ) .
main(). main(). public static.
5. new. , ,
( ). (
),
.
, .

.
( )
.
, .
6. Java .
. ,
(-

152

4.

). , .
7. this ,
. .
8. : , ,
. . , ,
.

5.
! .
!

, . .
, . ,
, , , , . .

. ,
, . . ,
, .
, .
, , , .
,
. .
,
. , , , . ,

154

5.

() . ,
, .
, , ,

(
). ,
, , , .
.
5.1 .
5.1.
// :
class OverloadDemo{
// :
void test(){
System.out.println(" !");
}
// :
void test(int a){
System.out.println(" int: "+a);
}
// double double:
double test(double a){
System.out.println(" double: "+a);
return a;
}}
// main():
class Overload{
public static void main(String args[]){
OverloadDemo obj=new OverloadDemo();
double result;
// :
obj.test();
obj.test(10);
result=obj.test(12.5);
System.out.println(": "+result);
}}

OverloadDemo, test(). ,
!.
.
int .

155

int: . , double double. double: ,


.
Overload main(),
test(). :
!
int: 10
double: 12.5
: 12.5

, ,
. , . 5.2.
5.2.
class OverloadDemo2{
// :
void test(){
System.out.println(" !");}
// :
void test(int a,int b){
System.out.println(" int: "+a+" "+b);}
// double:
void test(double a){
System.out.println(" double: "+a);}
}
class Overload2{
public static void main(String args[]){
OverloadDemo2 obj=new OverloadDemo2();
int i=88;
obj.test();
obj.test(10,20);
obj.test(i); // !
obj.test(12.5);
}}

OverloadDemo2 test(): ,
int double.
. main() Overload2
: , int,

156

5.

int double. ,
int OverloadDemo2 .
:
!
int: 10 20
double: 88.0
double: 12.5

. , test()
, , int
double, double.
OverloadDemo2 test()
int, .

,
.

. .

, . , , , , , :
;
, ;
,
.
, .
, , . ,

. .
5.3 , .
5.3.
class MyClass{
// :
double Re,Im;

157

// :
void show(){
System.out.println(" :\nRe="+Re+" Im="+Im);}
// :
MyClass(){
// :
System.out.println(" !");
// :
Re=0;
Im=0;
// :
show();}
}
class ConstrDemo{
public static void main(String[] args){
// :
MyClass obj=new MyClass();
}
}

MyClass Re Im double, show()


. , , . :
MyClass(){
System.out.println(" !");
Re=0;
Im=0;
show();}

MyClass() MyClass.
. .
.

. Re Im . , show() , .
:
!
:
Re=0.0 Im=0.0

, main()
MyClass MyClass obj=new MyClass(). ,
.

158

5.

, .
, .
.
. , . ,
.
5.4.
5.4.
class MyClass{
// :
double Re,Im;
// :
void show(){
System.out.println(" :\nRe="+Re+" Im="+Im);}
// :
MyClass(){
// :
System.out.println(" !");
// :
Re=0;
Im=0;
// :
show();}
// :
MyClass(double x){
// :
System.out.println(" !");
// :
Re=x;
Im=x;
// :
show();}
// :
MyClass(double x,double y){
// :
System.out.println(" !");
// :
Re=x;
Im=y;
// :
show();}
}
class ConstrDemo2{
public static void main(String[] args){

159

// :
MyClass obj1=new MyClass();
// :
MyClass obj2=new MyClass(10);
// :
MyClass obj3=new MyClass(100,200);
}
}

, , .

.
.
MyClass obj1=new MyClass() .
MyClass obj2=new MyClass(10) . MyClass obj3=new MyClass(100,200).
:
!
:
Re=0.0 Im=0.0
!
:
Re=10.0 Im=10.0
!
:
Re=100.0 Im=200.0

(
). (
), ( )
.
, Java.


, , ,
!

. .

( , ,
- ).

160

5.

. ,
return
. ,
. 5.5 , (
) , .
5.5.
class MyObjs{
// :
double Re,Im;
// :
void set(double Re,double Im){
this.Re=Re;
this.Im=Im;
show();}
// :
void show(){
System.out.println("Re="+Re+" "+"Im="+Im);}
// :
MyObjs(){
set(0,0);}
// :
MyObjs(double x){
set(x,x);}
// :
MyObjs(double x,double y){
set(x,y);}
// :
MyObjs(MyObjs obj){
set(obj.Re,obj.Im);}
// - :
MyObjs getSum(MyObjs obj){
// :
MyObjs tmp=new MyObjs();
// :
tmp.Re=Re+obj.Re;
tmp.Im=Im+obj.Im;
// :
return tmp;}
// "" :
void add(MyObjs obj){
Re+=obj.Re;

161

Im+=obj.Im;}
}
class ObjsDemo{
public static void main(String[] args){
// :
MyObjs a=new MyObjs(1);
MyObjs b=new MyObjs(-3,5);
MyObjs c=new MyObjs(b);
// "" :
c=a.getSum(b);
// :
c.show();
// :
a.add(c);
// :
a.show();
}
}

MyObjs Re Im, set() , show() , getSum(),


. ,
, , , .
, add() , ,
add() . add() ,
, , - .
getSum() MyObjs tmp=new MyObjs() ( ) tmp MyObjs. , tmp
, . tmp.Re=Re+obj.Re tmp.Im=Im+obj.Im tmp.Re tmp.Im
,
( Re Im), obj,
( obj.Re obj.Im). tmp , return tmp
.
. , ,
.
( ) .
,
, , ,

162

5.

. , , (, , c=a.
getSum(b) main()).
add() Re+=obj.Re Im+=obj.Im Re Im
, . , , , .
, , ,
, . .
. .
, . , ,
set(),
. , . , , set() .
set() . , set(). set()
- .
. ,
,
, .
:
Re=1.0 Im=1.0
Re=-3.0 Im=5.0
Re=-3.0 Im=5.0
Re=0.0 Im=0.0
Re=-2.0 Im=6.0
Re=-1.0 Im=7.0


. , ,
. , .
tmp getSum().
, . 5.6.

163

5.6.
class MyClass{
int n,m;
// :
MyClass(int a,int b){
n=a;
m=b;
System.out.println(" !");}
// "":
MyClass(MyClass obj){
n=obj.n+1;
m=obj.m-1;
System.out.println(" !");}
// :
void show(){
System.out.println(" : "+n+" "+m);}
}
class Nameless2{
public static void main(String args[]){
// - :
MyClass obj=new MyClass(new MyClass(10,100));
// :
obj.show();}
}

MyClass a b, show() . a b,
, . ,
. ,
.
MyClass obj=new MyClass(new MyClass(10,100))
obj MyClass. ,
, , new MyClass(10,100).
a b 10 100 .

obj. a b
11 99. :
!
!
: 11 99

:
( ),

164

5.

( obj).
obj.show(),
obj.

. .

Java :
.
. , ,
,
,
.
, .
,
.

, .
Java () , . , ,

. ,
.
, ( ) . , , .
new . , ,
. , ,
.
.5.1.
,
, . ,
, . , . , , - .

165

, . , ,
.

. 5.1.

Java ++ , Java . , ++
.
5.7 ,
.
5.7.
class Base{
int a,b;
void show(){
System.out.println(a+":"+b);}
}
class Test{
void f(int x,int y){
x*=2;
y/=2;
System.out.println(x+":"+y);}
void f(Base obj){
obj.a*=2;
obj.b/=2;
System.out.println(obj.a+":"+obj.b);}
}
class TestDemo{
public static void main(String args[]){
Base obj=new Base();
Test tstFunc=new Test();
obj.a=10;
obj.b=200;
tstFunc.f(obj.a,obj.b);
obj.show();

166

5.

5.7 ()
tstFunc.f(obj);
obj.show();}
}

Base a b, show(), .
Test f(). :
int - Base. f() ,
.
( ).
, :
, , .
TestDemo : obj
Base tstFunc Test. obj.a=10 obj.b=200
obj , tstFunc.f(obj.a,obj.b)
f(),
obj. , , 20:100. obj obj.show(),
10:200, , . , , ,
. f()
, .
tstFunc.f(obj) 20:100.
obj.show(). , . : , ,
.


,
, .


, ,
,
. ,

- .

167

, , ,

. ,
, (5.8).
5.8.
class InterpAndApprox{
// :
private int n;
// :
private double a,b;
// :
double[][] data;
// :
private double psi(int k,double x){
int i;
double s=1;
for(i=0;i<k;i++)
s*=(x-data[0][i])/(data[0][k]-data[0][i]);
for(i=k+1;i<=n;i++)
s*=(x-data[0][i])/(data[0][k]-data[0][i]);
return s;}
// :
private void setab(){
double Sxy=0,Sx=0,Sy=0,Sxx=0;
for(int i=0;i<=n;i++){
Sx+=data[0][i];
Sy+=data[1][i];
Sxx+=data[0][i]*data[0][i];
Sxy+=data[0][i]*data[1][i];}
a=((n+1)*Sxy-Sx*Sy)/((n+1)*Sxx-Sx*Sx);
b=Sy/(n+1)-a/(n+1)*Sx;
}
// :
double approx(double x){
return a*x+b;}
// :
double interp(double x){
double s=0;
for(int i=0;i<=n;i++)
s+=data[1][i]*psi(i,x);
return s;}
// :
InterpAndApprox(int n){

168

5.

5.8 ()
this.n=n;
data=new double[2][n+1];
for(int i=0;i<=n;i++){
data[0][i]=Math.PI*i/n/2;
data[1][i]=Math.sin(data[0][i]);}
setab();
}}
class InterpAndApproxDemo{
public static void main(String[] args){
double x;
int i,n=4,N=2*n;
InterpAndApprox obj=new InterpAndApprox(n);
System.out.printf("%60s"," :\n");
System.out.printf("%25s"," x");
System.out.printf("%25s"," y=sin(x)");
System.out.printf("%25s",". L(x)");
System.out.printf("%25s",". f(x)\n");
for(i=0;i<=N;i++){
x=i*Math.PI/N/2;
System.out.printf("%25s",x);
System.out.printf("%25s",Math.sin(x));
System.out.printf("%25s",obj.interp(x));
System.out.printf("%25s",obj.approx(x)+"\n");}
}}

InterpAndApprox, ,
,
.
InterpAndApprox ,
data . 2 ( 0 , 1 ),
n ( n+1 ).
. InterpAndApprox n. n
, data=new double[2][n+1] ,
data. . , i
0 n+1 , data[0][i]=Math.PI*i/n/2 data[1]
[i]=Math.sin(data[0][i]) . , y( x) = sin( x)
0 x 2 .
setab(). ,
data

169

. a b.
, .
,
{ x k } { y k } ( k = 0,1, 2, ..., n ), x y( x)
( y( x k ) = y k ) . ,
a b , f ( x) = ax + b ( ) .

, ,
y k f ( x k ) . ,
a b, :
n

k =0

k =0

( y k f ( x k )) 2 = ( y k ax k b) 2 .

, a b
:
n

a=

(n + 1) x k y k x k y k
k =0

k =0

k =0
2

(n + 1) x k2 x k
k =0
k =0
n

b=

1 n
a n
yk

xk .
n + 1 k =0
n + 1 k =0

Sx),

yk

k =0

( Sy),

xk yk

k =0

( Sxy)

k =0

x k (
k =0
x k2 ( Sxx),

setab()

. approx(), , . interp().

psi(). , .
.

170

5.

{ x k }
{ y k } ( k = 0,1, 2, ..., n ) () L( x) n x ,
,
L( x k ) = y k k = 0,1, 2, ..., n .
:
L( x) =

y k k ( x) .

k =0

:
k ( x) =

x xk
.
m xk

m =0,
m k

, k ( x m ) = km ,
km .
. psi(), interp().
,
InterpAndApprox, : , , .
. ,
printf(), . ,
. ,
"%25s" , ( ) 25 .
:
x
0.0
0.1963495408493
0.3926990816987
0.5890486225481
0.7853981633974
0.9817477042468
1.1780972450961
1.3744467859455
1.5707963267948

:
y=sin(x) . L(x)
0.0
0.0
0.1950903220161
0.1948971309247
0.3826834323651
0.3826834323650
0.5555702330196
0.5556486374881
0.7071067811865
0.7071067811865
0.8314696123025
0.8313962000794
0.9238795325112
0.9238795325112
0.9807852804032
0.9809437185526
1.0
1.0

. f(x)
0.0944947291833
0.2215545341906
0.3486143391979
0.4756741442052
0.6027339492125
0.7297937542198
0.8568535592272
0.9839133642345
1.1109731692418

171

,
, , , .
. , .


5.9 ,
. , , . (
), .
Figures n . , ,
. Figures Point. ( char)
name ( ). x y double
.

() , . dist() ,
.
. , show() , .
.
Math.round().
, , .
. : .
, .
. Point.
points Figures. points
, -
Point ( Point[] points).
n. n points
.
perimeter()
square() . dist(),

172

5.

Figures, Point, (
).
. ( p Point). Point p=newPoint('A',x,y). A, Figures.
this.n=n n ,
. points=new Point[n]
. phi0 r phi0=Math.atan2(y,x)
r=p.dist(). , Math.atan2(y,x)
x y. phi=2*Math.PI/n.
. show()
. ( )
p.
- points. ( p.name) .
p.name . char.
, p.name.
, , r
, x = r cos() y = r sin().
k- ( , ) = 0 + (k 1) , 0 ,
2
=
. n
.

.
5.9.
class Figures{
// :
private int n;
// ():
private Point[] points;
// :
Figures(int n,double x,double y){
// ,
// :
double phi0,phi,r;

173

// :
Point p=new Point('A',x,y);
// :
int i;
// :
this.n=n;
// - "":
points=new Point[n];
// - :
phi0=Math.atan2(y,x);
// - :
phi=2*Math.PI/n;
// :
r=p.dist();
System.out.print(" "+n+"- ");
// "" :
for(i=0;i<n-1;i++){
p.show();
System.out.print(i==n-2?" ":", ");
points[i]=p;
// "" :
p=new Point((char)(p.name+1),r*Math.cos(phi0+(i+1)*phi),r*Math.
sin(phi0+(i+1)*phi));
}
// "" :
points[n-1]=p;
p.show();
System.out.println(".");
// :
System.out.println(":\t"+perimeter()+".");
// :
System.out.println(":\t"+square()+".");
}
// :
double dist(Point A,Point B){
return Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));}
// :
double perimeter(){
double P=0;
int i;
for(i=0;i<n-1;i++)
P+=dist(points[i],points[i+1]);
P+=dist(points[n-1],points[0]);
return P;
}

174

5.

5.9 ()
// :
double square(){
double r=points[0].dist();
double phi=2*Math.PI/n;
double s=r*r*Math.sin(phi)/2;
return s*n;
}
// "":
class Point{
// :
char name;
// :
double x,y;
// :
Point(char name,double x,double y){
// :
this.name=name;
// :
this.x=x;
this.y=y;}
// :
double dist(){
return Math.sqrt(x*x+y*y);}
// :
void show(){
System.out.print(name+"("+Math.round(x*100)/100.0+","+Math.
round(y*100)/100.0+")");}
}
}
class FiguresDemo{
public static void main(String[] args){
// :
new Figures(4,1,1);}
}

, Figures,
main() FiguresDemo .
:
4- A(1.0,1.0), B(-1.0,1.0), C(-1.0,-1.0)
D(1.0,-1.0).
: 8.0.
: 4.000000000000001.

,

.

175

, , . , , ,
.
( , ),
( ).


, . , x :
exp( x) =

xk
.
k =0 k !

,
. , A , exp( A) ,
:
exp( A) =

Ak
.
k =0 k !

, A
E ( , 0
), A = E .
, ,
, . ,
: , .
( ) .

MatrixExp (5.10). matrix , . , MatrixExp. ,
, , .
5.10.
class MatrixExp{
// :
private final static int N=100;
// :
private int n;

176

5.

5.10 ()
// :
private double[][] matrix;
// ( ):
MatrixExp(int n,double Xmin,double Xmax){
double x=Math.abs(Xmax-Xmin);
int i,j;
this.n=n;
matrix=new double[n][n];
for(i=0;i<n;i++){
for(j=0;j<n;j++){
matrix[i][j]=x*Math.random()+Xmin;}
}}
// ( ):
MatrixExp(double[][] matrix){
this.n=matrix[0].length;
this.matrix=new double[n][n];
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
this.matrix[i][j]=matrix[i][j];}}
}
// ( ):
MatrixExp(int n){
this.n=n;
matrix=new double[n][n];
int i,j;
for(i=0;i<n;i++){
for(j=0;j<i;j++){
matrix[i][j]=0;}
matrix[i][i]=1;
for(j=i+1;j<n;j++){
matrix[i][j]=0;}}
}
// ( ):
MatrixExp(int n,double a){
this.n=n;
matrix=new double[n][n];
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
matrix[i][j]=a;}
}}
// :
void show(){
int i,j;
for(i=0;i<n;i++){

177

for(j=0;j<n-1;j++){
System.out.print(Math.round(1000*matrix[i][j])/1000.0+"\t");}
System.out.print(Math.round(1000*matrix[i][n-1])/1000.0+"\n");
}}
// :
MatrixExp sum(MatrixExp B){
MatrixExp t=new MatrixExp(n,0);
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
t.matrix[i][j]=matrix[i][j]+B.matrix[i][j];}}
return t;}
// :
MatrixExp prod(double x){
MatrixExp t=new MatrixExp(matrix);
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
t.matrix[i][j]*=x;}}
return t;}
// :
MatrixExp prod(MatrixExp B){
MatrixExp t=new MatrixExp(n,0);
int i,j,k;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
for(k=0;k<n;k++){
t.matrix[i][j]+=matrix[i][k]*B.matrix[k][j];}
}}
return t;}
// :
MatrixExp mExp(){
MatrixExp t,q;
// - :
t=new MatrixExp(n);
// :
q=new MatrixExp(matrix);
int i;
// :
for(i=1;i<=N;i++){
t=t.sum(q);
q=q.prod(this).prod(1.0/(i+1));}
return t;}
}
class MatrixExpDemo{
public static void main(String[] args){

178

5.

5.10 ()
// ( ):
MatrixExp A=new MatrixExp(3,-1,1);
System.out.println(" A:");
// :
A.show();
System.out.println(" exp(A):");
// :
A.mExp().show();
}}

, show() matrix,
sum() , prod() , mExp()
. , :
;
, ;
;
, .
MatrixExp. matrix, : (final) N , n - .
, , matrix, . : ,
- .

.
( , ,
). -
.
,
. ,
.
show() - .
.
matrix ,
.
, . .

179

sum() . MatrixExp. - matrix matrix , . MatrixExp. matrix


, .
.
prod() ,
MatrixExp. , - matrix
, . .
prod() MatrixExp . matrix
, , matrix ,
. ( ).
MatrixExp matrix, . MatrixExp,
( ), -
( ).
- . -,
-.
mExp() t q MatrixExp. t=new MatrixExp(n) q=new MatrixExp(matrix) .
,
t. .
( matrix), q.
, . ( -
matrix) . , k- Ak
q k q k =
, A k!
A
, . , q k +1 q k =
k +1
,
- ,
q, ( )

180

5.

1
, k k +1
.
- , q, (
) , t, t.
t=t.sum(q) ( mExp()).
- ,
q, q=q.prod(this).prod(1.0/
(i+1)). .
. q.prod(this)
(, q, , ,
mExp()), -. , . prod()
( q.prod(this).prod(1.0/(i+1))).
, , prod().
q. , prod()
.

mExp() , t.
MatrixExpDemo MatrixExp A=new
MatrixExp(3,-1,1) MatrixExp -
3, 1 1.
A.
A.show(). A.mExp().show()
, . A.mExp().
mExp() , MatrixExp -,
( A.mExp()) show(), .
:
,

0.844
0.891
-0.549

2.931
1.532
-1.131

A:
0.797 0.095
-0.407 -0.528
0.168 0.63
exp(A):
1.18 -0.111
1.068 -0.621
-0.121 1.825

181

, , ,
A .
, (
2,718). ,
, , ..



. 5.11.
5.11.
class Vector{
// - ():
private double[] vect=new double[3];
// :
void set(double x,double y,double z){
vect[0]=x;
vect[1]=y;
vect[2]=z;}
// :
void set(double[] params){
for(int i=0;i<3;i++)
vect[i]=params[i];}
void set(){
set(0,0,0);}
// :
void show(){
double[] x=new double[3];
for(int i=0;i<3;i++)
x[i]=Math.round(vect[i]*100)/100.0;
System.out.print("<"+x[0]+";"+x[1]+";"+x[2]+">");}
// :
void show(char s){
show();
System.out.print(s);}
// :
Vector plus(Vector b){
Vector t=new Vector();
for(int i=0;i<3;i++)
t.vect[i]=vect[i]+b.vect[i];
return t;}
// :
Vector minus(Vector b){
Vector t=new Vector();

182

5.

5.11 ()
for(int i=0;i<3;i++)
t.vect[i]=vect[i]-b.vect[i];
return t;}
// :
Vector prod(double x){
Vector t=new Vector();
for(int i=0;i<3;i++)
t.vect[i]=vect[i]*x;
return t;}
// :
double prod(Vector b){
double x=0;
for(int i=0;i<3;i++)
x+=vect[i]*b.vect[i];
return x;}
// :
Vector vprod(Vector b){
Vector t=new Vector();
for(int i=0;i<3;i++)
t.vect[i]=vect[(i+1)%3]*b.vect[(i+2)%3]-vect[(i+2)%3]*b.vect[(i+1)%3];
return t;}
// :
double mprod(Vector b,Vector c){
return vprod(b).prod(c);}
// :
Vector div(double x){
Vector t=new Vector();
for(int i=0;i<3;i++)
t.vect[i]=vect[i]/x;
return t;}
// :
double module(){
return Math.sqrt(prod(this));}
// ( ):
double ang(Vector b){
double z;
z=prod(b)/module()/b.module();
return Math.acos(z);}
// ( ):
double angDeg(Vector b){
return Math.toDegrees(ang(b));}
// :
double square(Vector b){
Vector t;
t=vprod(b);
return t.module();}

183

// :
Vector(double[] params){
set(params);}
// :
Vector(double x,double y,double z){
set(x,y,z);}
// :
Vector(){
set();}
}
class VectorDemo{
public static void main(String[] args){
Vector a=new Vector(1,0,0);
Vector b=new Vector(new double[]{0,1,0});
Vector c;
System.out.println(" :");
(c=a.vprod(b)).show('\n');
System.out.println(" : "+a.mprod(b,c));
System.out.println(" :");
a.prod(3).plus(b.div(2)).minus(c).show('\n');
a.set(4,0,-3);
b.set(0,10,0);
System.out.println(" ( ): "+a.angDeg(b));
System.out.println(" : "+a.square(b));}
}

Vector. vect. , .
set() vect.
double (
vect) ,
( -). , set()
set() .
set() . , set(),
set().
show(), ,
( char),
. ( )
. ,
, show() '\n'.

184

5.

. ,
plus() .
Vector, vect
vect . minus(), .
prod() ,
, . Vector, prod() (
vect ).
div(). vect .
,
c a b ( c = a b),
c a b
c k = a k +1bk + 2 a k + 2 bk +1 ,

..
vprod() % .
mprod().
( double). a b , c . b c Vector mprod().
vprod(). vprod(b).
prod(c), b c . ,
vprod(b) Vector, vect , mprod(), vect b.
vprod(b) prod(c) c (
mprod()).
module()
.
this.
ang() angDeg() ( ). ,
. , square()
. ,
, .

185

VectorDemo .
:
:
<0.0;0.0;1.0>
: 1.0
:
<3.0;0.5;-1.0>
( ): 90.0
: 50.0

:
(c=a.vprod(b)).show('\n');
a.prod(3).plus(b.div(2)).minus(c).show('\n');

c a.vprod(b), ,
- show() ( ). , a, b c,
3a + b 2 c .



.
Polynom, , , ,
. , 5.12.
5.12.
class Polynom{
// n-1:
private int n;
// :
private double[] a;
// :
void set(double[] a){
this.n=a.length;
this.a=new double[n];
int i;
for(i=0;i<n;i++)
this.a[i]=a[i];
}
//
// ( - ):
void set(int n,double z){

186

5.

5.12 ()
this.n=n;
this.a=new double[n];
int i;
for(i=0;i<n;i++)
this.a[i]=z;
}
//
// ( - , ):
void set(int n){
set(n,0);}
// :
double value(double x){
double z=0,q=1;
for(int i=0;i<n;i++){
z+=a[i]*q;
q*=x;}
return z;}
// :
void show(){
int i;
System.out.print(" x:\t");
for(i=0;i<n-1;i++){
System.out.print(" "+i+"\t");}
System.out.println(" "+(n-1));
System.out.print(":\t");
for(i=0;i<n-1;i++){
System.out.print(a[i]+"\t");}
System.out.println(a[n-1]);
}
// :
void show(double x){
System.out.println("
x="+x);
System.out.println(" P(x)="+value(x));
}
// :
Polynom diff(){
Polynom t=new Polynom(n-1);
for(int i=0;i<n-1;i++)
t.a[i]=a[i+1]*(i+1);
return t;}
// k:
Polynom diff(int k){
if(k>=n) return new Polynom(1);
if(k>0) return diff().diff(k-1);
else return new Polynom(a);
}

187

// :
Polynom plus(Polynom Q){
Polynom t;
int i;
if(n>=Q.n){
t=new Polynom(a);
for(i=0;i<Q.n;i++)
t.a[i]+=Q.a[i];}
else{
t=new Polynom(Q.a);
for(i=0;i<n;i++)
t.a[i]+=a[i];
}
return t;}
// :
Polynom minus(Polynom Q){
return plus(Q.prod(-1));}
Polynom div(double z){
return prod(1/z);}
// :
Polynom prod(double z){
Polynom t=new Polynom(a);
for(int i=0;i<n;i++)
a[i]*=z;
return t;}
// :
Polynom prod(Polynom Q){
int N=n+Q.n-1;
Polynom t=new Polynom(N);
for(int i=0;i<n;i++){
for(int j=0;j<Q.n;j++){
t.a[i+j]+=a[i]*Q.a[j];}
}
return t;}
// :
Polynom(double[] a){
set(a);
}
Polynom(int n,double z){
set(n,z);}
Polynom(int n){
set(n);}
}
class PolynomDemo{
public static void main(String[] args){

188

5.

5.12 ()
// :
double[] coefs=new double[]{3,-2,-1,0,1};
// :
Polynom P=new Polynom(coefs);
System.out.println("\t :");
// :
P.show();
System.out.println("\t :");
// :
P.show(1);
System.out.println("\t :");
// :
Polynom Q=P.diff(2);
// ():
Q.show();
System.out.println("\t :");
// ():
Q.plus(P).show();
System.out.println("\t :");
// ():
Q.prod(P).show();
}}

Polynom n
( n-1,
n ), - a ( double)
.
a set().
, , ,
, (
). set()
, .
value() double , , .
show() : double. . show()
( double),
.
Polynom , .

189

. ,
, -. y = x n
dy
dy
= nx n 1,


dx
dx
n
, P ( x) = a k x k
k =0
-:
n

n 1

n 1

k =1

k =0

k =0

P ( x) = ka k x k 1 =

(k + 1)a k +1 x k bk x k.

- bk a k bk = (k + 1)a k +1 k = 0,1, ..., n 1 ,


bn = 0. , , , , . ,
- diff(),
Polynom.
, , .
Polynom t=new Polynom(n-1) t, , , . ( ),
a ( ). i t.a[i]=a[i+1]*(i+1) -. t
.
diff() . , .
k ( )
( n-1), if(k>=n) return new Polynom(1)
, ( ),
. , , .
( ) diff().diff(k-1).
, new Polynom(a).
. , ,
.
diff().diff(k-1).
diff()
. , diff().diff(k-1)

190

5.

, k k 1 . . ( ),
-. diff(k-1) ,
.
plus() Polynom, ,
.
, , .
,
, , - a
. ,
-. . (,
- ), .
.
minus(). prod()
, - minus(),
1, plus() ,
minus(). -
plus(Q.prod(-1)) Q
Polynom, minus(). prod(),
( Polynom)
. prod() double.
. prod() Polynom,
( ,
- ).
Polynom. ( - ) . -, n m, n + m.
, ,
- - , . int N=n+Q.n-1,
Q Polynom, prod(). N - -
prod(). ,
, Polynom t=new Polynom(N).
- t .

191

, - , .
- t.a[i+j]+=a[i]*Q.a[j].
, a . , i j -,
i+j , i+j.
,
n

P ( x) = a i x i Q( x) =
i =0

b j x j,
j =0

:
n

i =0

j =0

R( x) P ( x)Q( x) = a i x i b j x j =

0 i n,
0 j m

a i b j x i + j.

, -
k, a i b j
i + j =k

, k. .
Polynom
set(), , , .
PolynomDemo, , Polynom.
. , Polynom
Q=P.diff(2) P
, Q. , Q.plus(P).show() ( Q.plus(P)),
show().
:
:
x:
0
1
2
:
3.0
-2.0
-1.0
:

x=1.0
P(x)=1.0
:
x:
0
1
2
:
-2.0
0.0
12.0
:
x:
0
1
2
:
1.0
-2.0
11.0

3
0.0

3
0.0

4
1.0

4
1.0

192
:
x:
0
1
:
-6.0
4.0

2
38.0

3
-24.0

5.

4
-14.0

5
0.0

6
12.0

,
. ,
show() Polynom.
, . toString().
, , toString()
8.


,

. , . , , . ( char) Level
: ,
A, B, , ,
C .. , Number. . , A 1. B 1 2.
C 1 4 ..
.5.2.

. 5.2.

,
.
(
IDnum).

193

, , ID ObjectTree ( 5.13). . ()
getID(). ID[i]=(int)(Math.random()*10)
( (int)(Math.
random()*10)) ID.
showID(). ID,
. show(), , ,
: ,
.
FirstRef SecondRef
ObjectTree .
. 5.13.
5.13.
class ObjectTree{
// ID- :
private static int IDnum=8;
// ():
private char Level;
// :
private int Number;
// ( ):
private int[] ID;
// :
ObjectTree FirstRef;
// :
ObjectTree SecondRef;
// ID- :
private void getID(){
ID=new int[IDnum];
for(int i=0;i<IDnum;i++)
ID[i]=(int)(Math.random()*10);
}
// ID- :
private void showID(){
for(int i=0;i<IDnum;i++)
System.out.print("|"+ID[i]);
System.out.print("|\n");
}

194

5.

5.13 ()
// :
void show(){
System.out.println(" : \t"+Level);
System.out.println(" : \t"+Number);
System.out.print("ID- : \t");
showID();
}
// :
ObjectTree(int k,char L,int n){
System.out.println("\t !");
Level=L;
Number=n;
getID();
show();
if(k==1){
FirstRef=null;
SecondRef=null;
}
else{
// :
FirstRef=new ObjectTree(k-1,(char)((int)L+1),2*n-1);
SecondRef=new ObjectTree(k-1,(char)((int)L+1),2*n);}
}}
class ObjectTreeDemo{
public static void main(String[] args){
// :
ObjectTree tree=new ObjectTree(4,'A',1);
System.out.println("\t !");
// :
tree.FirstRef.SecondRef.FirstRef.show();
}}

: , , .
,
.
,

Level Number. getID() show() . .

. ( ,
), - FirstRef SecondRef
( null), ,

195

. ,
,
, FirstRef SecondRef :
FirstRef=new ObjectTree(k-1,(char)((int)L+1),2*n-1);
SecondRef=new ObjectTree(k-1,(char)((int)L+1),2*n);


. L (char)
((int)L+1). (int)L L, , , ( (char)).
n 2*n-1. 2*n. ,
1,
. , : , . ,
,
, ()
.
ObjectTree tree=new ObjectTree(4,'A',1)
,
: show()
( tree.FirstRef.SecondRef.FirstRef.show()). :
!
:
A
:
1
ID- :
|3|5|1|1|1|1|5|0|
!
:
B
:
1
ID- :
|3|6|4|8|2|2|2|9|
!
:
C
:
1
ID- :
|7|6|7|8|9|1|5|7|
!
:
D
:
1
ID- :
|5|6|6|1|6|6|5|4|

196
!
: D
: 2
ID- :
|3|6|5|0|2|1|6|7|
!
: C
: 2
ID- :
|7|6|0|9|6|1|0|2|
!
: D
: 3
ID- :
|9|2|6|2|5|5|9|9|
!
: D
: 4
ID- :
|8|7|7|0|1|2|1|4|
!
: B
: 2
ID- :
|1|7|3|8|8|1|9|2|
!
: C
: 3
ID- :
|9|3|2|4|7|9|4|7|
!
: D
: 5
ID- :
|7|9|6|4|9|4|4|4|
!
: D
: 6
ID- :
|0|9|5|4|5|5|7|4|
!
: C
: 4
ID- :
|4|1|6|6|9|7|8|1|
!
: D
: 7
ID- :
|6|4|7|5|0|0|0|3|
!
: D
: 8
ID- :
|3|9|9|6|7|3|6|3|

5.

197

!
:
D
:
3
ID- :
|9|2|6|2|5|5|9|9|

(..5.2) , 1.
2. 2, 3, 4 .. tree.FirstRef.SecondRef.FirstRef.
show() show() D 3.
.

1. Java . . ,
, () .
,
.
2. ,
. .
,
. . ,
, new _().
3. , . , ,
.
4. :
. ,
,
. . Java
, .

6.

,
.

, , Java, .
. , , .
. -,
. -,
. , .
, , : , , .
.
() .
. ,
, , . , . , ,
, .
.


- ,
- . !

, .
,

199

, .
extends .
( ,
). :
class A extends B{
//
}

A B. A () B.
, Java, ++, , Java
. Java, ++,
: , , .
. 6.1 .
6.1.
class A{ //
int i,j;
void showij(){
System.out.println(" i j: "+i+" "+j);}
}
class B extends A{ //
int k;
void showk(){
System.out.println(" k: "+k);}
void sum(){
// :
System.out.println(" i+j+k="+(i+j+k));}
}
class AB{
public static void main(String arg[]){
// :
A SuperObj=new A();
// :
B SubObj=new B();
SuperObj.i=10;
SuperObj.j=20;
SuperObj.showij();
SubObj.i=7;
SubObj.j=8;

200

6.

6.1 ()
SubObj.k=9;
SubObj.showij();
SubObj.showk();
SubObj.sum();}
}

A,
i j, showij() .
A B ( A).
B k, showk() sum() k i, j k. ,
i j B , B
, ( B
i j) .
main() AB : SuperObj A
SubObj B. i j SuperObj 10 20 , showij()
.
i, j k SubObj 7, 8 9.
showij() i j, k showk(). ,
sum(). :
i j: 10 20
i j: 7 8
k: 9
i+j+k=24

, , i j,
showij() B.
.


,
.

. .

. . , . ,
private, , , . ,
, , .

201

, , , 6.2.
6.2.
class MySuperClass{ //
// :
private int a;
// :
private void showa(){
System.out.println(" a: "+a);}
// :
void seta(int n){
a=n;
showa();}
}
class MySubClass extends MySuperClass{ //
int b;
void setall(int i,int j){
seta(i);
b=j;
System.out.println(" b: "+b);}
}
class PrivateSuperDemo{
public static void main(String arg[]){
// :
MySubClass obj=new MySubClass();
obj.setall(1,5);}
}

:
a: 1
b: 5

. MySuperClass, ( private)
a . showa()
a. seta() a seta()
showa(). , seta()
a, ,
showa().
MySubClass b
setall(). , MySubClass MySuperClass seta(). a showa()
MySubClass .

202

6.

. MySubClass setall() , ,
MySuperClass seta(), , ,
a showa(). ,
, , , setall() obj MySubClass
a, obj . .
, . , ,
. , , ,
. ,
, , ,
.
,
.
. ,
, . ,
. .

. .

(
, ),
,
. , . : , - ,
.
. ,
(, ).
,
, . super, ,

203

. .
, :
_(1){
super(2); //
//
}

super , ( ).
6.3.
6.3.
// :
class MySuperClass{
int a;
void showa(){
System.out.println(" a="+a);}
// :
MySuperClass(){
a=0;
showa();}
MySuperClass(int i){
a=i;
showa();}
}
// :
class MySubClass extends MySuperClass{
double x;
void showx(){
System.out.println(" x="+x);}
// :
MySubClass(){
super(); //
x=0;
showx();}
MySubClass(int i,double z){
super(i); //
x=z;
showx();}
}
class SuperConstrDemo{

204

6.

6.3 ()
public static void main(String[] args){
System.out.println(" :");
MySubClass obj1=new MySubClass();
System.out.println(" :");
MySubClass obj2=new MySubClass(5,3.2);}
}

:


:

a=0
x=0.0
a=5
x=3.2

. MySuperClass a, showa() ,
: . a .
. showa() a .
MySuperClass MySubClass.
x double showx() .
: . super
.
super() .
( int
double), int
( super(i) ).
MySubClass. ,
.


.
!

205

, .
,
: , . .
.
, ,
, .
, 6.4.
6.4.
// :
class MyClassA{
// :
int number;
// :
MyClassA(){
number=0;
System.out.println(" "+number);}
// :
void showA(){
System.out.println(" number: "+number);}
}
// :
class MyClassB extends MyClassA{
// :
int number;
// :
MyClassB(){
super(); //
number=100;
System.out.println(" "+number);}
// :
void showB(){
System.out.println(" number: "+number);}
}
class TwoFieldsDemo{
public static void main(String[] args){
// :
MyClassB obj=new MyClassB();
// :
obj.number=50;
// :
obj.showA();
obj.showB();
}}

206

6.

:
0
100
number: 0
number: 50

MyClassA number, showA() ,


number .
MyClassB, MyClassA,
number. showB()
number,
number,
100. , MyClassB
: number. ,
showB(), number , .
main() TwoFieldsDemo obj
MyClassB. new MyClassB() :
0
100


.
number 0 . .
number ( ) 100 . , number obj 0 100.
number obj.number=50 , . ,
number, 100, 50.
number obj.showA()
, : showA() , , . obj.showB() number, .
, , super, ,
. .
, ( ), super._. , showB()

207

number ,
super.number. 6.5 ,
,
number.
6.5.
// :
class MyClassA{
// :
int number;
// :
MyClassA(int a){
number=a;
System.out.println(" "+number);}
// :
void showA(){
System.out.println(" number: "+number);}
}
// :
class MyClassB extends MyClassA{
// :
int number;
// :
MyClassB(int a){
super(a-1); //
number=a;
//
// :
System.out.println(" : "+super.number+" "+number);}
// :
void showB(){
// :
System.out.println(" "+super.number+" "+number);}
}
class TwoFieldsDemo2{
public static void main(String[] args){
// :
MyClassB obj=new MyClassB(5);
// :
obj.number=10;
// :
obj.showA();
obj.showB();
}}

208

6.

,
, number. ,
showA().
.
number, .
, .
.

, , ,
number, , ,
super.number. showB().
, number, ( obj.number=10), showA() showB().
:
4
: 4 5
number: 4
4 10

, , .
, , .
.


.
, !

, ,
, , . ,
, , . ,
super.

. ,
. ,

209

( , ). . . ,
,
, .
- , .
. ,
, ,
. : , , , .
,
, .
6.6 .
6.6.
class ClassA{
static int count=0;
private int code;
int number;
ClassA(int n){
set(n);
count++;
code=count;
System.out.println(" "+code+" !");}
void set(int n){
number=n;}
void show(){
System.out.println(" "+code+":");
System.out.println(" number: "+number);}
}
class ClassB extends ClassA{
char symbol;
ClassB(int n,char s){
super(n);
symbol=s;}
void set(int n,char s){
number=n;
symbol=s;}
void show(){
super.show();
System.out.println(" symbol: "+symbol);}
}
class MyMethDemo{

210

6.

6.6 ()
public static void main(String[] args){
ClassA objA=new ClassA(10);
ClassB objB=new ClassB(-20,'a');
objA.show();
objB.show();
objB.set(100);
objB.show();
objB.set(0,'z');
objB.show();}
}

:
1 !
2 !
1:
number: 10
2:
number: -20
symbol: a
2:
number: 100
symbol: a
2:
number: 0
symbol: z

. ClassA (), ClassB.


ClassA number,
count ( )
code. , ( number), set() number, show() number.
count .

. ClassA count++.
set()
number ( ),
code=count code. code
, .
count ,
. code count code
.

211

code ( ) . ( code) show(), ,


number.
ClassB ClassA. ClassB count number. code . , ClassB
symbol. :
int number char symbol.
ClassB :
super(n) symbol=s (n s ).
. . -, number . -, count . , ,
, . -, code ,

. ,
code.
show() ClassB .
ClassB show() show(),
ClassA. ClassA show()
number, ClassB show()
symbol. show() () ClassA.
super.show(). ,
, ( )
code .
set() ClassB . ClassA
, .
set() , : . ClassB
set() . ClassA,
ClassB.
ClassA objA=new ClassA(10) ClassB
objB=new ClassB(-20,'a') : objA objB . 1 ! 2 !
.
objA.show() objB.show(). show() ,

212

6.

show(), ClassA,
show(), ClassB. objA ( ) , objB .
objB.set(100) set() objB. , , ClassA. number objB,
symbol .
objB.show() (. ). objB.set(0,'z'),
set(), ClassB.
objB.show() , objB.


,
.

( )
Java , . .
6.7.
6.7.
class A{
int a;
A(int i){
a=i;
System.out.println(" a: "+a);}
}
class B extends A{
int b;
B(int i,int j){
super(i);
b=j;
System.out.println(" b: "+b);}
}
class C extends B{
int c;
C(int i,int j,int k){
super(i,j);
c=k;
System.out.println(" c: "+c);}
}

213

class MultiCall{
public static void main(String args[]){
C obj=new C(1,2,3);}
}

: A B.
B, , C. , . A
a .
. ,
.
B a A b. , .
( A), b. ,
a .
a b C. c.
( B),
c. C
.
a b .
C obj=new C(1,2,3)
C. :
a: 1
b: 2
c: 3


. . ,
6.8.
6.8. ,

class A{
void show(){
System.out.println(" ");}
}
class B extends A{
void show(String msg){
System.out.println(msg);}
}
class C extends B{
void show(){

214

6.

6.8 ()
System.out.println(" C");}
}
class MultiOverride{
public static void main(String args[]){
A obj1=new A();
B obj2=new B();
C obj3=new C();
obj1.show();
obj2.show();
obj2.show(" ");
obj3.show();
obj3.show(" ");}
}

, : A, B,
C.
, A
show(). .6.1.

. 6.1. show()

, show() A
. B . , B show() , ,
. , ,
String. , , .
C show() ,
B.

. show() (
, ). :


215

A . B ( A)
( , B). C C, B.

,
.
!
, ,
, , . , , ,
.
new . , (, )
(
).
, ,
. 6.9.
6.9.
class ClassA{
double Re;
void set(double x){
Re=x;}
void show(){
System.out.println(" A:");
System.out.println(" Re: "+Re);}
}
class ClassB extends ClassA{
double Im;

216

6.

6.9 ()
void set(double x,double y){
Re=x;
Im=y;}
void show(){
System.out.println(" B:");
System.out.println(" Re: "+Re);
System.out.println(" Im: "+Im);}
}
class SuperRefs{
public static void main(String[] args){
ClassA objA;
ClassB objB=new ClassB();
objA=objB;
objB.set(1,5);
objB.show();
objA.set(-10);
objA.show();}
}

ClassA,
ClassB. ClassA doubleRe set()
show(). show()
(- ) Re. set()
, Re.
Re ClassB.
doubleIm. set() ,
Re Im. show(),
.
ClassAobjA objA ClassA. ClassB objB=new ClassB()
ClassB, objB ClassB. objA=objB
objA.
, objA, objB
. , .
objA
ClassB.
objB.set(1,5) Re Im 1 5
. objB.show()
. show(), ClassB.
objA.set(-10) Re.
set(), ClassA ClassB.
objA set()
ClassB, . objA.

217

show() ClassB show().


:
B:
Re:
Im:
B:
Re:
Im:

1.0
5.0
-10.0
5.0

, objA
Re , Im.

,
, .
, , ,
, . , show()
objA ClassA ClassB, ,
, . ,
6.10.
6.10.
class A{
void show(){
System.out.println(" ");}
}
class B extends A{
void show(){
System.out.println(" ");}
}
class C extends A{
void show(){
System.out.println(" C");}
}
class Dispatch{
public static void main(String args[]){
A a=new A();
B b=new B();
C c=new C();
A ref;
ref=a;

218

6.

6.10 ()
ref.show();
ref=b;
ref.show();
ref=c;
ref.show();}
}

A, : B C. .6.2 .

. 6.2.

A show(),
A. B C .
show() B B,
C C.
a, b c
A, B C, ref A.
a, b c ( ref=a, ref=b ref=c). A
B, C, .
ref
ref.show() show(). :


C

,
show() ( ref.show()),
, ref.

Java , .
,
, ( , ). abstract,

219


.
, , . abstract.

.
. ( ). 6.11.
6.11.
// :
abstract class A{
// :
abstract void callme();
// :
void callmetoo(){
System.out.println(" ");}
}
// :
class B extends A{
// :
void callme(){
System.out.println(" ");}
}
class AbstDemo{
public static void main(String args[]){
// :
B obj=new B();
obj.callme();
obj.callmetoo();}
}

: A,
B. A
call() () callmetoo().
B. call() , B.
call() , callmetoo() .
. :

,
.

220

6.

, ,
, , . . , ,
, , . , , .
, .
.
final. ,
.
final (). ,
.


,
.


6.12 ,
:
,
. ,
.
6.12.
// :
class Compl{
// :
double Re,Im;
// :
Compl sum(Compl obj){
Compl tmp=new Compl();
tmp.Re=Re+obj.Re;
tmp.Im=Im+obj.Im;
return tmp;}
// :
Compl prod(Compl obj){
Compl tmp=new Compl();

221

tmp.Re=Re*obj.Re-Im*obj.Im;
tmp.Im=Im*obj.Re+Re*obj.Im;
return tmp;}
//
// :
Compl prod(double x){
Compl tmp=new Compl();
tmp.Re=Re*x;
tmp.Im=Im*x;
return tmp;}
// :
void show(){
System.out.println(" Re="+Re);
System.out.println(" Im="+Im);}
// :
Compl(){
Re=0;
Im=0;}
// :
Compl(double x){
Re=x;
Im=0;}
// :
Compl(double x,double y){
Re=x;
Im=y;}
// :
Compl(Compl obj){
Re=obj.Re;
Im=obj.Im;}
}
// :
class ComplNums extends Compl{
// :
private int n;
// :
ComplNums CExp(){
// - :
Compl tmp=new Compl(1);
// - :
Compl q=new Compl(this);
// :
int i;
// :
for(i=1;i<=n;i++){
tmp=tmp.sum(q);

222

6.

6.12 ()
q=q.prod(this).prod(1.0/(i+1));}
// - :
return new ComplNums(tmp);}
// :
ComplNums(){
super();
n=100;}
// :
ComplNums(double x){
super(x);
n=100;}
// :
ComplNums(double x,double y){
super(x,y);
n=100;}
// :
ComplNums(double x,double y,int m){
super(x,y);
n=m;}
//
// :
ComplNums(Compl obj){
super(obj);
n=100;}
// :
ComplNums(ComplNums obj){
super(obj);
n=obj.n;}
}
class ComplExtendsDemo{
public static void main(String[] args){
ComplNums z=new ComplNums(2,3);
// :
z.CExp().show();}
}

Compl Re Im double. ,
sum() , Compl.
prod() ,
. Compl , , , .

.

223

Compl ComplNums.
, n,
. z ,
, :
exp( z)

zk

z2

zn

k ! = 1 + z + 2! + ... + n ! .

k =0

.
.
, .
CExp().
, .
. Compl tmp=new Compl(1)
tmp .
.
q. Compl q=new Compl(this). .
, .
, .
, , .
. . tmp=tmp.sum(q)
. q=q.prod(this).prod(1.0/(i+1)) (
i, ). this.
newComplNums(tmp) , .
:
Re=-7.315110094901102
Im=1.042743656235904

, , , . . ,
. .

224

6.


(
).
. 6.13. ,
, , .
6.13.
// :
class PolyBase{
// :
double[] a;
// :
double value(double x){
double s=0,q=1;
for(int i=0;i<a.length;i++){
s+=a[i]*q;
q*=x;}
return s;}
// :
int power(){
for(int i=a.length-1;i>0;i--){
if(a[i]!=0) return i;}
return 0;}
// :
void show(){
System.out.println(" :");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.print("\n : ");
System.out.println(power()+".\n");}
}
// :
class PolyDerive extends PolyBase{
// :
PolyBase prod(PolyBase Q){
int i,j,n;
n=power()+Q.power()+1;
PolyBase tmp=new PolyBase();
tmp.a=new double[n];
for(i=0;i<=power();i++){
for(j=0;j<=Q.power();j++){
tmp.a[i+j]+=a[i]*Q.a[j];}

225

}
return tmp;}
// :
void show(double x){
System.out.println(" : "+x);
System.out.println(" : "+value(x));
show();}
PolyDerive(PolyBase obj){
a=new double[obj.a.length];
for(int i=0;i<a.length;i++)
a[i]=obj.a[i];}
}
// :
class Taylor extends PolyDerive{
void show(){
System.out.println(" !");
super.show();
}
Taylor(PolyBase P,PolyBase Q){
super(P);
PolyBase tmp=prod(Q);
for(int i=0;i<a.length;i++)
a[i]=tmp.a[i];}
}
class PolyExtendsDemo{
public static void main(String[] args){
// :
PolyBase P=new PolyBase();
PolyBase Q=new PolyBase();
PolyBase R;
P.a=new double[]{1,-2,4,1,-3};
Q.a=new double[]{2,-1,3,0,4};
// :
R=new PolyDerive(P).prod(Q);
R.show();
new PolyDerive(P).show(-1);
// :
new Taylor(P,Q).show();
}}

PolyBase, ,
a double. (,
2
n
a 0 + a1 x + a 2 x + ... + a n x ). , value() ( ). power() .

226

6.

. ,
,
, . power() , , .
.
show() , - a. .
PolyDerive PolyBase.
prod(), . , , PolyBase. ,
. show() ,
, , ,
, .
. . ,
. ,
a , .
PolyDerive Taylor, .
.
, n, n, - ( 2n ) n.
Taylor show() ,
,
. show()
, super.show().
show(), PolyDerive PolyBase.
Taylor
PolyBase.
. ,
, Taylor, .
( Taylor PolyDerive)

227

( PolyBase). tmp
. tmp
a Taylor.
, ,
Taylor - , -
.
PolyExtendsDemo . :
:
2.0 -5.0 13.0 -8.0 9.0
: 8.

-2.0

7.0

4.0

-12.0

: -1.0
: 3.0
:
1.0 -2.0 4.0 1.0 -3.0
: 4.
!
:
2.0 -5.0 13.0 -8.0 9.0
: 4.

, (P, Q R) PolyBase.
(P Q) a ,
( R) . new PolyDerive(P) P
PolyBase PolyDerive,
prod() . PolyDerive show().

new Taylor(P,Q).show().
.

1. Java . . ,
, ,
. .
2. extends , .

228

3.

4.
5.

6.

7.

8.

9.

6.

,

(
. ).
,
.
super. , .
.
super ( ).
. . ()
super.
.
Java ( ) , . .
.
,
.
Java .
, .
. . abstract.
.
,
final.

II.
Java

7.
.

. ,
, .
,
.

Java
, !

, .
, , . , .
, , .
, , .
. ,
. , . .
,
, package , :
package mypack;

mypack . , ( ) .
, . ,

Java

231

package .
package .
.

, , (
), ( ). (, ) , . Java :
. , ,
package java.awt.image, ,
image java/awt/image.

, , . .7.1 .
7.1.

private

protected

public

(+) , , (-) .
, . ,
.
public ,
: , .
private , , .
, .
, protected,
.

232

7.

,
,
, .
. , public ( ). public, . public ,
.
,
, : , . ,
MyClass subpack mypack, :
mypack.subpack.MyClass

,
. import
( ). .
() . , import
( ), :
import mypack.subpack.MyClass

(*), :
import mypack.subpack.*

, .
.
java.lang ( )
.
,
.
, .

, , , ,
.

. -

, Java
.

233

, .
.
.
. , ,
- (, ).
,
class interface. , .
(
final) ( static). ,
.
.
. . , , .
.
, .

implements(). , ,
, , :
class [extends ] implements 1,2,...{
//
}

,
extends ,
implements. implements ,
. ,
class public,
.
7.1 , .
7.1.
// :
interface MyMath{

234

7.

7.1 ()
// :
double Sinus(double x);
// :
double PI=3.14159265358979;
}
// :
class MyClass implements MyMath{
// ( ):
public double Sinus(double x){
int i,n=1000;
double z=0,q=x;
for(i=1;i<=n;i++){
z+=q;
q*=(-1)*x*x/(2*i)/(2*i+1);}
return z;}
}
class MyMathDemo{
public static void main(String args[]){
MyClass obj=new MyClass();
// :
double z=MyClass.PI/6;
// :
System.out.println("sin("+z+")="+obj.Sinus(z));}
}

MyMath, MyClass MyMathDemo.


MyClass MyMath. MyMathDemo
.
MyMath ( ) Sinus().
double .
, PI double. . , final, static ,
. , .
MyClass, , MyMath. , MyClass. :
sin( x) = x

x3 x5 x7
+

+ ...
3! 5! 7!

obj MyClass
z double. /6.
PI, MyMath.
MyClass,

235

MyClass.PI.
, PI. z .
:
sin(0.5235987755982984)=0.4999999999999995

1/2.
, ++, ,
. .
, Java (, ). ,
, , . ,
.
, ,

.

. -


. ,
, ,
. , , . ,
.
, . ,
, , .
7.2 , .

236

7.

7.2.
// :
interface Base{
int F(int n);
}
// A Base:
class A implements Base{
// :
public int F(int n){
if(n==1||n==2) return n;
else return n*F(n-2);}
}
// B Base:
class B implements Base{
// :
public int F(int n){
if(n<1) return 1;
else return n*F(n-1);}
}
class ImplDemo{
public static void main(String args[]){
// :
Base refA=new A();
Base refB=new B();
// :
A objA=new A();
B objB=new B();
// :
System.out.println("1: "+refA.F(5));
System.out.println("2: "+refB.F(5));
System.out.println("3: "+objA.F(5));
System.out.println("4: "+objB.F(5));
// :
refA=objB;
refB=objA;
// :
System.out.println("5: "+refA.F(5));
System.out.println("6: "+refB.F(5));}
}

Base F(),
. A B
Base, -. A F() , (, n ,

237

n !! = n(n 2)(n 4)...). B F() ( 1 n , n ! = n(n 1)(n 2)...1). F()


.
Base refA=new A() Base refB=new B()
A B, refA refB.
Base,
.
A B,
objA objB .
AobjA=newA() BobjB=newB().

F() 5. , 5!!=15 5!=120.
, A,
15, , B, 120.
, objA refA , A, objB
refB , B.
refA=objB refB=objA : refA B, refB A. refA.F(5)
F() B, refB.F(5) F(),
A. :
1:
2:
3:
4:
5:
6:

15
120
15
120
120
15

7.3 , .
7.3.
// :
interface One{
void setOne(int n);
}
// :
interface Two{
void setTwo(int n);
}

238

7.

7.3 ()
// :
class ClassA{
int number;
void show(){
System.out.println(" number: "+number);}
}
// :
class ClassB extends ClassA implements One,Two{
int value;
// :
public void setOne(int n){
number=n;}
// :
public void setTwo(int n){
value=n;}
// :
void show(){
super.show();
System.out.println(" value: "+value);}
}
class MoreImplDemo{
public static void main(String[] args){
// :
One ref1;
Two ref2;
// :
ClassB obj=new ClassB();
// :
ref1=obj;
ref2=obj;
// :
ref1.setOne(10);
ref2.setTwo(-50);
// :
obj.show();}
}

:
number: 10
value: -50

. ,
One Two, ClassB. ,
ClassB ClassA.
: One setOne(), Two setTwo().
.

239

ClassA intnumber show(),


. ClassB
, : number int value, .
ClassB setOne() setTwo() ,
number, value.
: ref1 One ref2 Two. ,
obj ClassB. obj. , ClassB
One Two. ref1 setOne(),
ref2 setTwo(). ref1.setOne(10) ref2.setTwo(-50)
obj , obj.show() .

. -

, .
. ,
extends.
, :
interface 1 extends 2{
//
}

7.4 .
7.4.
// :
interface BaseA{
int FunA(int n);
}
// :
interface BaseB extends BaseA{
int FunB(int n);
}

240

7.

7.4 ()
// :
class MyClass implements BaseB{
public int FunA(int n){
if(n<1) return 1;
else return n*FunA(n-1);}
public int FunB(int n){
if(n==1||n==2) return n;
else return n*FunB(n-2);}
}
class ImplExtDemo{
public static void main(String args[]){
MyClass obj=new MyClass();
System.out.println("1: "+obj.FunA(5));
System.out.println("2: "+obj.FunB(5));}
}

:
1: 120
2: 15

, .
BaseA FunA().
. BaseB ()
BaseA. BaseB FunB()
. BaseA FunA(), BaseB FunA() FunB(). MyClass,
BaseB, . FunA() - ,
FunB()
. obj MyClass FunA() FunB(). , .

1. Java .
, , package,
.
2.
.
3. , (
), - ( ).

241

, , interface.
4. . ,
(public). .
implements.
5. , ,
.
,
.
6. ,
. ,
extends.

8.
.
. ?

. .

. , , . Java .
Java-: String StringBuffer.
. . , , .
, String ,
StringBuffer . , String StringBuffer.
,
.
String StringBuffer java.lang, , String StringBuffer
.
(final), .

String
, ,
.


String. , , ,
, . String,
.

String

243

.
. String
:
String s=new String();

.
.
, .
:
char symbols[]={'a','b','c'};
String s=new String(symbols);

, ,
, ,
. , :
char symbols={'a','b','c','d','e','f'};
String s=new String(symbols,2,3); // s="cde"

.
,
.
, . :
String obj=new String(" ");
String s=new String(obj);

. , , byte
, , .
, , .
8.1
, .
8.1.
class MakeString{
public static void main(String args[]){
char symbs[]={'J','a','v','a'};
String strA=new String(symbs);
String strB=new String(strA);
System.out.println(strA);
System.out.println(strB);}
}


Java. : symbs,

244

8.

strA,
strB ( Java), strA.
, strA strB
String , .
- , , srtA,
(
strA=strB).
. .
8.2.
. byte ASCII.
8.2.
class SubStringConstr{
public static void main(String args[]){
byte ascii[]={65,66,67,68,69,70};
String strBig=new String(ascii);
System.out.println(strBig);
String strSmall=new String(ascii,2,3);
System.out.println(strSmall);}
}

, ascii. String. : ,
2 ( , ). :
ABCDEF
CDE

, String .
. ,
, . , ,
.
( ).
, , length().
, . , str String, , str,
str.length(). , Java String. , length()

String

245

. , ,
( 12):
" !".length()

,
( +), () . :
String str=" "+18+" .";

"18.".
(, ),
( String). . :
String str=" : "+1+2;

,
String, str, : " :12".
" :"+1+2. 1 2
" :", , , " :" ( )
"1",
"2". , :
String str=" : "+(1+2);

: , . str " :3".



, , , .
toString(). ,
.


Stringstr="";

str
String, "". ,
. , , Java String.

246

8.

, :
Stringstr;
str="";

str String.
, . , .
. "" String, str="" str. ,
, .

toString()
, .

toString() Object,
Java ( Java).
. , , .
.
toString(), , .
String . , . :
println().
toString() . 8.3.
8.3. toString()
class ComplNums{
// :
double Re;
double Im;
// :
ComplNums(double x,double y){
Re=x;
Im=y;}
// toString():
public String toString(){
String result="",sign="",ImPart="",RePart="";

toString()

247

if(Re!=0||(Re==0&&Im==0)) RePart+=Re;
if((Im>0)&&(Re!=0)) sign+="+";
if(Im!=0) ImPart+=Im+"i";
result=RePart+sign+ImPart;
return result;}
}
class toStringDemo{
public static void main(String[] args){
for(int i=1;i<=3;i++){
for(int j=1;j<=5;j+=2){
ComplNums z=new ComplNums(i-2,j-3);
// toString():
System.out.println(z);
}
}
}
}

. ComplNums Re Im double.
. Re Im. , toString(). , public, String
. toString()
. .
, , .
, ,
() .
, ,
.
,
.
toString() . , result String. result,
, : RePart
( ), ImPart
(
i) sign (
). .
if(Re!=0||(Re==0&&Im==0)) RePart+=Re , , . ,
, .

248

8.

if((Im>0)&&(Re!=0)) sign+="+"
. , ,
.
sign ,
Im.
if(Im!=0)
ImPart+=Im+"i". , , "i". , .
z ComplNums. :
, .
:
-1.0-2.0i
-1.0
-1.0+2.0i
-2.0i
0.0
2.0i
1.0-2.0i
1.0
1.0+2.0i

z. System.out.println(z),
println(). toString()
z ( String).
toString() ,

, .


, .
?
, !

String ,
. . , 8.4.

249

8.4.
class getCharsDemo{
public static void main(String args[]){
// :
String s=" Java";
// :
char buf[]=new char[9];
s.getChars(s.length()-9,s.length(),buf,0);
System.out.println(buf);
// :
char symbol;
symbol=s.charAt(21);
System.out.println(symbol);
// :
System.out.println("--------------------------");
// :
byte nums[];
nums=s.getBytes();
for(int i=0;i<s.length();i++){
System.out.print(nums[i]+" ");
if((i+1)%6==0) System.out.println();}
// :
System.out.println("\n--------------------------");
char chars[]=new char[s.length()];
chars =s.toCharArray();
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' ') System.out.println("-->");
else System.out.print(chars[i]+" * ");}
}
}

s . buf
9 . s.
getChars() ( s.getChars(s.length()-9,s.
length(),buf,0)). :
, , , , ,
.
s.length()-9 s.length()-1 , buf, buf[0].
System.out.println(buf)

println().

250

8.

charAt().
( , , ).
.
.
nums ( byte[]). getBytes() , nums.
, , .
nums . nums s.
chars. , ,
toCharArray().
,
.
chars ,
, .
:
Java

--------------------------49 -16 -24 -20 -27 -16


32 -14 -27 -22 -15 -14
-18 -30 -18 -23 32 -15
-14 -16 -18 -22 -24 32
-106 32 -1 -25 -5 -22
32 74 97 118 97
------------------------- * * * * * * -->
* * * * * * * * * -->
* * * * * * -->
* -->
* * * * -->
J * a * v * a *

, ,
. .

251


!
,
.

. equals()
equalsIgnoreCase(). ,
, . equals() true,
, .
.
,
false. equalsIgnoreCase()
.
, . ,
.
, (==) (!=), ,
. , ,
.
, strA strB.
String strA String strB,
. strA==strB strA!=strB,
strA strB, , . strA strB () . , strA==strB
true, strA strB
. , false. .
8.5 ,
.
8.5.
class equalStringsDemo{
public static void main(String args[]){
String strA=" ";

252
8.5 ()
String strB=new String("
String strC=" ";
String strD=" ";
System.out.println(strA+"
System.out.println(strA+"
System.out.println(strA+"
System.out.println(strA+"
equalsIgnoreCase(strD));
System.out.println(strA+"
}}

8.

");

,
,
,
,

"+strB+"
"+strC+"
"+strD+"
"+strD+"

-->
-->
-->
-->

"+strA.equals(strB));
"+strA.equals(strC));
"+strA.equals(strD));
"+strA.

, "+strB+" --> "+(strA==strB));

,
,
,
,
,

-->
-->
-->
-->
-->

true
false
false
true
false

. strA,
strB, strC strD .
, strA strB, .
, strD,
. , strC, , .

equals(), equalsIgnoreCase() ==. .
strA strB
equals() .
strA strC false .
strA strD. strA strD equalsIgnoreCase(), . . ,
strA strB
( strA==strB), false, .
, String strB=new String(" ")
String strB=" " ( ,
strA), strA==strB true. : strA strB
, String.
( ) ,
.

253


, !

,
, . indexOf() lastIndexOf(). ( char) ( String). .
( , ). indexOf()
, lastIndexOf()
.
.
, 1. 8.6 , .
8.6.
class indexOfDemo{
public static void main(String args[]){
String s=" -\n"+
" , .\n"+
" , - \n"+
" !";
System.out.println(s);
System.out.println("1: "+s.indexOf(''));
System.out.println("2: "+s.lastIndexOf(''));
System.out.println("3: "+s.indexOf(""));
System.out.println("4: "+s.indexOf('',10));
System.out.println("5: "+s.indexOf("",10));}
}

s String,
. , , .
. indexOf()
lastIndexOf() '' "",
, (
) . :
-
, .
, -

254

8.

!
1: 5
2: 53
3: 27
4: 11
5: 27

\n .

.


,
.

, String .
. , - ( String), , -, String , -, ,
.
. StringBuffer,
.
.8.1 ,
.
8.1.

substring()

substring() ( String) , .

.

concat()

concat() :
, ,
, .
String

replace()

replace() (char) .
,

255

trim()

trim() ,

.

toLowerCase()

toLowerCase()
( String),
(
).

toUpperCase()

toUpperCase()
( String),
(
).


8.7.
8.7.
class StringReplace{
public static void main(String args[]){
String str=" ++";
String s,s1,s2,s3,s4;
// :
s=str.substring(3,21);
System.out.println(s);
// :
s1=str.concat(" Java");
System.out.println(s1);
// :
s2=s1.replace(' ','_');
System.out.println(s2);
// :
s3=s1.toLowerCase();
System.out.println(s3);
// :
s4=s1.toUpperCase();
System.out.println(s4);
}}


:

++ Java
___++__Java
++ java
++ JAVA

256

8.

. str :
"++"

, String. s=str.substring(3,21) str 4- 21-


, ( "")
s. .
s1 str "Java"
:
s1=str.concat("Java")

s1 :
++Java

s2=s1.replace(' ','_') , s2 s1
. s2
:
___++__Java

s3=s1.toLowerCase() s3,
s1. s4=s1.toUpperCase()
, s1. s3 s4
:
++java
++JAVA

StringBuffer
,
.

String,
StringBuffer.
, StringBuffer . , StringBuffer, , . ,
StringBuffer
.
StringBuffer.

StringBuffer

257

StringBuffer ,
StringBuffer(),
( String StringBuffer).

StringBuffer ,
16- ( ).
StringBuffer,
. .
StringBuffer
.8.2.
8.2. StringBuffer

length()

capacity()


( ,
, )

ensureCapacity()

setLength()

(
)

charAt()


( )

setCharAt()

: .
, .

getChars()

. :

, , , ,

append()

insert()

, .

reverse()

258

8.

delete()

.
,

deleteCharAt()

replace()


. ,
.
,

,
String. 8.8.
8.8. StringBuffer
class StringBufferDemo{
public static void main(String args[]){
// - StringBuffer:
StringBuffer str=new StringBuffer(" ++");
// :
System.out.println(str.length());
// ( ):
System.out.println(str.capacity());
// :
str.insert(20,"Java ");
// :
System.out.println(str);
// :
str.replace(27,30,"Pascal");
// :
System.out.println(str);
// :
str.reverse();
// :
System.out.println(str);}
}

StringBuffer str=new StringBuffer("


++") StringBuffer ++, str.
System.out.println(str.length()) ( )
. ( ) System.out.println(str.capacity()). ,

259

++ 23 . 16 39 .
StringBuffer 16 .
str.insert(20,"Java ") str, 20- (
21- ), "Java". :
Java++

str str.
replace(27,30,"Pascal"). , 27-
29- ( ++),
Pascal. str :
JavaPascal

, str.reverse() str
. :
23
39
Java ++
Java Pascal
lacsaP avaJ

, StringBuffer, . , ( ), .
.
: length() capacity().
String . .


,
, .

. .

,
.

.

260

8.

Java
(
) main(). 8.9
, .
8.9.
class CommandLine{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]: "+args[i]);
}}

args,
main(). i 0 args.
length-1 (, length , Java ).
args ( String). ,
System.out.println("args["+i+"]:"+args[i]) .
:
java CommandLine : 100 -1

, :
args[0]=
args[1]=
args[2]=
args[3]=:
args[4]=100
args[5]=
args[6]=-1


, , , , , main(),
, String .

1. Java String StringBuffer.


2. ,
String StringBuffer, , , .
,

261

. String ,
.
StringBuffer
,
.
3. ( String StringBuffer) Java
,
.
4. String (,
println()) toString().

.
5.
main(). , main(),
.

9.

, , ,
, . , .
.
, , ,
.
.

, . , Java, ,
.
.


,
.

, . Java , ().
, . , . , .

( ).

263

, (,
) ,
, . ,
, . , , ,
, , , , , .
,
. -, , . -,
, , , .
Java try-catchfinally. try ,
, . , catch.
, ,
, . , , catch, catch , ,
.
try ,
catch. catch ,

catch.
try catch finally , ,
.
try-catch-finally :
try{
// ,
}
catch(__1 ){
//
}
catch(__2 ){
//
}
...

264

9.

finally{
// ,
}

try{} ,
finally ( ), try-catch-finally .
try
catch. , ,
finally ( ).
, try-catch-finally.
, try ,
catch . . Java, ,
,
throws. . , .
.
, , . , .
, , , . throw.


.
.

Java ,
.
Throwable. : Exception Error.
Error ,
, . Exception RuntimeException. RuntimeException , .

265

RuntimeException .
, , , (
).
9.1 ,
, .
9.1.
class ExceptionDemo{
public static void main(String args[]){
int a,b;
// :
try{
b=0;
// :
a=100/b;
}catch(ArithmeticException e){
// :
System.out.println(" !");
}
System.out.println(" !");}
}

, , . a b. b , a
a=100/b. ,
! ,
. ,
a=100/b , , ,
,
.
ArithmeticException, RuntimeException. ,
, try,
try catch. catch e
ArithmeticException ( ).
e ,
.
, ,
:
System.out.println("!")

!.
.

266

9.

catch
System.out.println(" !"). :
!
!

, ,
.
9.2.
9.2.
// Random:
import java.util.Random;
class ArithExcepionDemo{
public static void main(String args[]){
int a=0,b=0,c=0;
// :
Random r=new Random();
for(int i=0;i<32000;i++){
try{
b=r.nextInt(200);
c=r.nextInt(100);
// :
a=10000/b/c;
}catch(ArithmeticException e){
// :
System.out.println(" !");
a=0;}
System.out.println("a="+a);}
}
}

, . . Random.
, ,
import java.util.Random java.util.
a, b c
. Random r=new Random() r
Random. nextInt(), r. . .
. b=r.nextInt(200), c=r.
nextInt(100) a=10000/b/c. b c , ,

267

a=10000/b/c . try.
catch{},
, System.out.println(" !")
a=0.
, a .
. , a .
, , , :
...
a=1
!
a=0
a=18
a=2
...

, catch ( ) . , .


, .

Throwable toString(), , ,
Object, ,
,
. , toString() , ,
println() . 9.3.
9.3.
class MoreExceptionDemo{
public static void main(String args[]){
int a,b;
try{
b=0;
// :
a=100/b;

268

9.

9.3 ()
}catch(ArithmeticException e){
// :
System.out.println(": "+e);}
System.out.println(" !");}
}


, System.out.println(": "+e)
println() e.
:
: java.lang.ArithmeticException: / by zero
!

, , :
e .

catch{}
,

, catch .
( ) . 9.4
, .
9.4. catch
import java.util.Random;
class MultiCatchDemo{
public static void main(String args[]){
Random r=new Random();
int MyArray[]={0,2};
int a,b;
for(int i=1;i<10;i++){
try{
a=r.nextInt(3);
b=10/MyArray[a];
System.out.println(b);
}catch(ArithmeticException e){
System.out.println(" !");}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(" !");}

catch{}

269

finally{System.out.println("**************");}}
System.out.println(" for !");}
}

, , import java.util.Random
Random, Random r=new Random() r
. , MyArray ( 0 2),
a b.
a=r.nextInt(3) a 0 2 . a,
, 0, 1 2. b=10/MyArray[a]
b.
. -, a 0, , MyArray[0] . -, a 2, , MyArray[2] .
a 1, b
5 System.out.println(b).
catch
ArithmeticException. , .
,
, ArrayIndexOutOfBoundsException. catch.
, .
, finally , , -
. :
!
**************
!
**************
!
**************
5
**************
!
**************
5
**************
!

270

9.

**************
5
**************
!
**************
for !

, .

try
, .

try try. ,
try try
catch , try catch
.
, , , try, try. try
, ,
try, .

try , try .
(
).
9.5 try.
9.5. try
import java.util.Random;
class NestTryDemo{
public static void main(String args[]){
Random r=new Random();
int a,b;
int c[]={-1,1};
for(int i=1;i<10;i++){
try{
a=r.nextInt(3);
// 0,1 2
b=100/a;
//
System.out.println("b="+b);

try

271

try{
if(a==1) a=a/(a-1);
//
else c[a]=200;
//
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(" : "+e);}
}catch(ArithmeticException e){
System.out.println(" : "+e);}
System.out.println("*******************************");}
}}

, ( r
Random), a b, c, ( 1 1).
try a=r.nextInt(3)
b=100/a , a , , ,
. catch
try. :
System.out.println(":"+e)

e ArithmeticException catch.
, b ( : 100 a 1 50
a 2), ,
try. , , ( ArrayIndexOutOfB
oundsException).
:
System.out.println(":"+e)

try,
. , a .
, a=a/(a-1) . ( a
) c[a]=200. ,
try , a 1
2, 0,
, catch try. try a
, , a 2.
c[a]=200
, c , c[2]
.

272

9.

, try . try
, catch try. :
b=50
: java.lang.ArrayIndexOutOfBoundsException:
*******************************
b=100
: java.lang.ArithmeticException: / by zero
*******************************
b=50
: java.lang.ArrayIndexOutOfBoundsException:
*******************************
: java.lang.ArithmeticException: / by zero
*******************************
b=50
: java.lang.ArrayIndexOutOfBoundsException:
*******************************
b=50
: java.lang.ArrayIndexOutOfBoundsException:
*******************************
b=100
: java.lang.ArithmeticException: / by zero
*******************************
b=100
: java.lang.ArithmeticException: / by zero
*******************************
: java.lang.ArithmeticException: / by zero
*******************************

try 9.6.
try , try.
9.6. try
import java.util.Random;
class MethWithTryDemo{
static void nesttry(int a){
int c[]={-1,1};
try{
if(a==1) a=a/(a-1); //
else c[a]=200;
//
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(" : "+e);}
}
public static void main(String args[]){
Random r=new Random();

273

int a,b;
for(int i=1;i<10;i++){
try{
a=r.nextInt(3);
// 0, 1 2
b=100/a;
//
System.out.println("b="+b);
nesttry(a);
}catch(ArithmeticException e){
System.out.println(" : "+e);}
System.out.println("*******************************");}
}}

, , ,
try nesttry(), try. , try,
nesttry(). , ,
try. .

, ,
, . throw. :
throw _;

throw , ,
. . , Throwable . . -, catch,
-, new.
.
( RuntimeException)
.
, ,
, (, print() println()).
throw , .
catch.

274

9.

, .
9.7.
9.7.
class ThrowDemo{
static void demoproc(){
try{
// :
NullPointerException ExObj=new NullPointerException("!");
throw ExObj; //
}catch(NullPointerException e){
System.out.println(" demoproc!");
throw e;
//
}}
public static void main(String args[]){
try{
demoproc();
}catch(NullPointerException e){
System.out.println(" : "+e);}
System.out.println(" !");}
}

:
demoproc!
: java.lang.NullPointerException: !
!

ThrowDemo, main(), demoproc(), . :


NullPointerExceptionExObj= newNullPointerException("!")

, ExObj NullPointerException ( ). NullPointerException


"!".
. throw ExObj . try, catch . catch
, , .
, demoproc().
System.out.println(" demoproc!")

throwe .
, try
catch .
demoproc() try NullPointerException

275

( System.out.println(" : "+e)), demoproc()


.
. -,
demoproc() ExObj
,
:
thrownewNullPointerException("!")

, ,
. -, : java.
lang.NullPointerException: !
demoproc(), ! . , , .
demoproc() (
ExObj) catch.
e, . .
ExObj. catch throwe, , catch.
ExObj. demoproc()
, try catch , catch
ExObj, !.
println() . ( java.lang.
NullPointerException:).


, .

, , , . throws
, . , ,
.
throws, . ,

276

9.

. ,
Error, RuntimeException . RuntimeException.
, (
), :
_ _() throws 1,2,...{
//
}

, . , , 9.8.
9.8.
class ThrowsDemo{
// :
static void throwOne() throws IllegalAccessException{
System.out.println(" throwOne!");
// :
throw new IllegalAccessException(" !");}
public static void main(String args[]){
try{
throwOne(); //
}catch(IllegalAccessException e){ //
System.out.println(" : "+e);}
}}

:
throwOne!
: java.lang.IllegalAccessException: !

,
throwOne() , IllegalAccessException ( ).
throwOne() , :
thrownewIllegalAccessException("!")

IllegalAccess
Exception, . ,
throws IllegalAccessException. , ,
throws ( ) .

277

throwOne(), . () catch.

Java . , , . .9.1
Java.
9.1. Java

ArithmeticException

(,
)

ArrayIndexOutOfBoundsException

ArrayStoreException

ClassCastException

IllegalArgumentException

IndexOutOfBoundsException

NegativeArraySizeException

NullPointerException

NumberFormatException

StringIndexOutOfBoundsException

UnsupportedOperationException

Java .9.2.
9.2. Java

ClassNotFoundException

IllegalAccessException

278

9.

9.2 ()

InstantiationException

InterruptedException

NoSuchFieldException

NoSuchMethodException

, , . ,
.


?
!

Java
, . Java .

Exception, , , Throwable.
.
Exception, ,
Throwable. Throwable .9.3.
9.3. Throwable

fillInStackTrace()

Throwable, .
(

getLocalizesMessage() String) .

getMessage()

( String) .

printStackTrace()

toString()

String, .

279

9.9 , .
9.9.
// :
class MyException extends Exception{
private double min;
private double max;
private String error;
// :
MyException(double x,double y,String str){
min=x;
max=y;
error=str;}
// toString():
public String toString(){
return " ("+error+"): ["+min+","+max+"]";}
}
class MyExceptionDemo{
// :
static double MyLog(double x) throws MyException{
if(x<0||x>1) return Math.log(x*(x-1));
else throw new MyException(0,1," ");
}
public static void main(String args[]){
double x=-1.2,y=1.2,z=0.5;
try{
System.out.println("ln("+x+")="+MyLog(x));
System.out.println("ln("+y+")="+MyLog(y));
System.out.println("ln("+z+")="+MyLog(z));
}catch(MyException e){//
System.out.println(e);}
}
}

:
ln(-1.2)=0.9707789171582248
ln(1.2)=-1.427116355640146
( ): [0.0,1.0]

MyException,
Exception. :
min max double error, String. toString().

280

9.

,
.
MyLog() double.
double. MyException.
x
:
ln( x ( x 1)) .
, MyLog(), [0,1] ,
Math.log(x*(x-1)) (
log(),
Math). MyLog() [0,1] , , . MyLog()
MyException.
[0,1]
( ).
MyLog() . MyException.
, , , . println()
catch, toString() MyException.

1. Java
, , . () , , .
() .
2.
. throw,
.
3. try-catch-finally. try , catch
( ), finally , .
4. Java ,
Throwable. -

281

.
,
throws
.
5. , .
Exception ( Throwable).

10.

Java . , . .
. , , , . .
, . , .
.
.
, .
, .

Java
, . , .
!


,
, . .
,
,

Java

283

. , .
Java.
Java, ,
. Thread Runnable. Thread,
Runnable. Thread .
Java- . , . .

.
.
.
.
Thread.
.10.1.
10.1. Thread

currentThread()

getName()

(
)

getPriority()


( )

isAlive()

join()

run()

sleep()


( , )

start()

run()

, currentThread(), Thread public static.


public static Thread currenThread(). currentThread() 10.1.

284

10.

10.1.
class CurrentThreadDemo{
public static void main(String args[]){
// t Thread:
Thread t;
// t :
t=Thread.currentThread();
// :
System.out.println(" : "+t);
// () :
t.setName(" ");
// :
System.out.println(" : "+t);
try{
for(int n=5;n>0;n--){
System.out.println(n);
// :
Thread.sleep(1000);}
}catch(InterruptedException e){ // " "
System.out.println(" !");}}
}

Thread t
t Thread. , , t=Thread.currentThread() (, : Thread t=Thread.currentThread()). currentThread()
, , , , ,
, .
, .
. t
. ,
, t.
: .
, t .
, , ,
.
System.out.println(" :"+t) . t, println(), ( Thread
toString()). :
:Thread[main,5,main]

Thread[main,5,main]
.
Thread : , .
main, 5,

285

main.
. . , , .
,
, . .
. .
t.setName(" ") . "" setName(),
.
System.out.println(" : "+t)
:
: Thread[,5,main]

5 1.
Thread.sleep(1000) . :
: Thread[main,5,main]
: Thread[ ,5,main]
5
4
3
2
1

(
).
sleep() InterruptedException
( ) , . main() , InterruptedException.


.
!

, ( ) Thread, Runnable.
Runnable.
,
Runnable. Runnable

286

10.

run(). , . , run()
. run() :
publicvoidrun()

start().
Runnable .
1. , Runnable. run().
2. Thread.
: , Runnable,
.
3. Thread start().
, ,
, Runnable,
, , run(), , Runnable. Java Thread.
.
( run()). ,
Runnable. Thread
.
, start(), ( Thread).
.
1. Runnable ( ) run(), Thread.
2. Thread ( ), Thread, . Thread,
this. ,
,
.
3.
( Thread) start(). .
4. , Runnable.
,
,
.

287

Runnable
10.2.
10.2. Runnable
// , Runnable:
class NewThread implements Runnable{
// - :
Thread t;
// :
NewThread(){
// :
t=new Thread(this," ");
// :
System.out.println(" : "+t);
t.start();
//
}
// run():
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println(" : "+i);
// :
Thread.sleep(500);}
}
//
catch(InterruptedException e){
System.out.println(" !");}
System.out.println(" !");
}
}
class ThreadDemo{
public static void main(String args[]){
// NewThread:
new NewThread();
//
try{
for(int i=5;i>0;i--){
System.out.println(" : "+i*100);
// :
Thread.sleep(1000);}
}
// :
catch(InterruptedException e){
System.out.println(" !");}
System.out.println(" !");}
}

288

10.

NewThread, Runnable. t Thread.


NewThread t=new Thread(this," ") t
Thread.
NewThread, t ( this),
"
". System.out.println(" : "+t)
, t.start() . ,
NewThread, .
NewThread run().
0,5 " : "
5 1 1. Thread.sleep(500). , run()
InterruptedException ( ) .
ThreadDemo new NewThread()
NewThread, .
" : " 500 100
100. ,
sleep(),
InterruptedException.
:
: Thread[ ,5,main]
: 500
: 5
: 4
: 3
: 400
: 2
: 1
: 300
!
: 200
: 100
!

, (): , 0,5 .
,
,
, ,
.

289

Thread. , Thread Runnable. ,


Runnable , () Thread. run() Thread - .
, Thread .
Runnable, ,
Thread, () run() Thread start(). , , , , . ,
, Thread,
Thread, ,
Runnable - Thread. .
10.3
Thread.
10.3. Thread
// NewThread Thread:
class NewThread extends Thread{
// :
NewThread(){
// Thread:
super(" ");
// :
System.out.println(" : "+this);
// :
start();
}
// run():
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println(" : "+i);
// :
Thread.sleep(500);}
}
// :
catch(InterruptedException e){
System.out.println(" !");}
System.out.println(" !");}
}
class ExtendsThreadDemo{
public static void main(String args[]){
new NewThread();

290

10.

10.3 ()
try{
for(int i=5;i>0;i--){
System.out.println(" : "+i*100);
Thread.sleep(1000);}
}catch(InterruptedException e){
System.out.println(" !");}
System.out.println(" !");
}}

:
: Thread[ ,5,main]
: 500
: 5
: 4
: 3
: 400
: 2
: 1
: 300
!
: 200
: 100
!

, , , . -. NewThread,
Thread, run().
super("") Thread . :
System.out.println(" : "+this)

this
. start() .
, , .

, ,
. 10.4 ,
.

291

10.4.
// Date:
import java.util.Date;
// NewThread Thread:
class NewThread extends Thread{
// (, , ):
private String name;
private int time;
private int count;
// :
NewThread(String name,int time,int count){
super(name);
this.name=name;
System.out.print(" : "+name+". ");
// :
System.out.println(": "+new Date()+".");
this.time=time;
this.count=count;
// :
start();}
// run():
public void run(){
try{
for(int i=1;i<=count;i++){
System.out.print(": "+name+". "+i+" "+count+". ");
// :
System.out.println(": "+new Date()+".");
// :
Thread.sleep(time);}
}catch(InterruptedException e){
System.out.println(" "+name);}
finally{
System.out.print(" \""+name+"\" ! ");
// :
System.out.println(": "+new Date()+".");}
}}
class MultiThreadDemo{
// InterruptedException main() :
public static void main(String args[]) throws InterruptedException{
System.out.print(" ! ");
// :
System.out.println(": "+new Date()+".");
// :
new NewThread("",5000,5);
new NewThread("",6000,4);
new NewThread("",7000,3);

292

10.

10.4 ()
// :
Thread.sleep(30000);
System.out.print(" ! ");
// :
System.out.println(": "+new Date()+".");
}}


, . .
, NewThread, Thread,
, :
.
, .
( ) name,
time count .
run(), NewThread
( ), .
count (, ,
). ( name), , , .
Date.
Date import java.util.Date ,
new Date(). println() .
Thread.sleep(time)
time ( )
NewThread.

. , ,
.
MultiThreadDemo
.
NewThread, :
newNewThread("",5000,5);
newNewThread("",6000,4);
newNewThread("",7000,3);

Thread.sleep(30000) 30 , .

293

( ).
:
! : Sat Sep 19 23:39:36 EEST 2009.
: . : Sat Sep 19 23:39:36 EEST 2009.
: . : Sat Sep 19 23:39:36 EEST 2009.
: . : Sat Sep 19 23:39:36 EEST 2009.
: . 1 5. : Sat Sep 19 23:39:36 EEST 2009.
: . 1 4. : Sat Sep 19 23:39:36 EEST 2009.
: . 1 3. : Sat Sep 19 23:39:36 EEST 2009.
: . 2 5. : Sat Sep 19 23:39:41 EEST 2009.
: . 2 4. : Sat Sep 19 23:39:42 EEST 2009.
: . 2 3. : Sat Sep 19 23:39:43 EEST 2009.
: . 3 5. : Sat Sep 19 23:39:46 EEST 2009.
: . 3 4. : Sat Sep 19 23:39:48 EEST 2009.
: . 3 3. : Sat Sep 19 23:39:50 EEST 2009.
: . 4 5. : Sat Sep 19 23:39:51 EEST 2009.
: . 4 4. : Sat Sep 19 23:39:54 EEST 2009.
: . 5 5. : Sat Sep 19 23:39:56 EEST 2009.
"" ! : Sat Sep 19 23:39:57 EEST 2009.
"" ! : Sat Sep 19 23:40:00 EEST 2009.
"" ! : Sat Sep 19 23:40:01 EEST 2009.
! : Sat Sep 19 23:40:06 EEST 2009.

, ,
. .
, main()
InterruptedException. , (throws InterruptedException).


, !
, !


. ,
.
, .
, ,
,

294

10.

, - .
. ,
.
.
, , . ,
. ,
. , 10000 .
5000 , 3000 . ,
12000 . . 10000 . , , .
, 15000 .
,
7000 , 10000 3000= 7000. ,
, . : .
, ( ).
(, ). ,
, ,
, ,
.
, , .
:
;
.
synchronized. , synchronized .
,
.
.
, synchronized,
.
10.5.

295

10.5.
class MySource{
// :
synchronized void showName(String msg1,String msg2,int time){
try{
// , :
Thread.sleep(time);
// msg1:
System.out.print(" : "+msg1);
// :
Thread.sleep(2*time);
// msg2:
System.out.println(" : "+msg2);
}catch(InterruptedException e){//
System.out.println(" : "+e);}
}}
// , Runnable:
class MakeThread implements Runnable{
// :
Thread t;
// - MySource:
MySource src;
// :
String name;
String surname;
int time;
// :
MakeThread(String s1,String s2,int time, MySource obj){
surname=s1;
name=s2;
src=obj;
this.time=time;
// :
t=new Thread(this);
// :
t.start();}
// run():
public void run(){
src.showName(surname,name,time);}
}
class SynchThreads{
public static void main(String args[]){
// "":
MySource obj=new MySource();

296

10.

10.5 ()
// :
MakeThread fellow1=new MakeThread("","",1000,obj);
MakeThread fellow2=new MakeThread("","",450,obj);
MakeThread fellow3=new MakeThread("","",1450,obj);
try{
//
fellow1.t.join();
fellow2.t.join();
fellow3.t.join();
}catch(InterruptedException e){ //
System.out.println(" : "+e);}
}}

, , . ,
:
. MySource, , showName . ,

, .
main() SynchThreads
MySource obj=new MySource(). MySource
10.5. showName(),
synchronized . : .
,

. , , , , .
sleep(). showName() InterruptedException .
MakeThread,
Runnable. : t Thread,
, src MySource, name surname
time. src
MySource,
. name , surname . time . MakeThread
, surname, name, time
src . t=newThread(this) ,
t.start() .

297

run() src.showName(surname,name,time) src showName().


MakeThread, .
, obj, fellow1,
fellow2 fellow3 MakeThread ( ).
join(), - t fellow1, fellow2 fellow3, .
:
: :
: :
: :

, . showName(). synchronized showName().


:
: : :
: :
:

, -
- obj, .

, ( , ).
, -. :
public void run(){
src.showName(surname,name,time);
}

run() MakeThread :
public void run(){
synchronized(src){
src.showName(surname,name,time);
}
}

,
synchronized src.

298

10.

1. Java ,
.
2. , Thread Runnable.
3. Thread, Runnable.
4. Java- . . .
5.
( Thread). run() ,
start() .
6. . ,
. synchronized. , .

11. -
.
, , .

, . , Java
-. , ( , )
. ,
.
Java . Java , . Java ,
, - . , .
Java - (stream)1.
: . ,
, ,
, , .

. , () java.io.

(thread), 10.

300

11. -


,
.

:
InputStream OutputStream. read() write(),
.
.11.1.
11.1.

InputStream

OutputStream

FilterInputStream

, InputStream

FilterOutputStream

, OutputStream

BufferedInputStream

BufferedOutputStream

ByteArrayInputStream

ByteArrayOutputStream

FileInputStream

FileOutputStream

DataInputStream


Java

DataOutputStream


Java

PrintStream

,
print() println()

- Reader Writer. read()


write()
.
.11.2.
11.2. Java

Reader

Writer

System.in

301


FilterReader

FilterWriter

InputStreamReader

OutputStreamWriter

StringReader

StringWriter

FileReader

FileWriter

BufferedReader

BufferedWriter

PrintWriter

,
print() println()

CharArrayReader

CharArrarWriter

LineNumberReader

-
System. System : in, out err.
public static. :
System.out . . System.out PrintStream.
System.in .
. InputStream.
System.err . . PrintStream.
- .

System.in
, , .

Java System.in.
BufferedReader
. () java.io
( import java.io.* ). BufferedReader
Reader.

302

11. -

, Reader ,
InputSrtreamReader. InputSrtreamReader . InputSrtreamReader
InputStream. , System.in.
( br):
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

BufferedReader. BufferedReader InputStreamReader.



System.in.
, Input
StreamReader ,
. InputStreamReader
BufferedReader, . , , ( ).
read() BufferedReader.
:
intread()throwsIOException

, IOException ( -
). , . char.
readLine() Buffered
Reader. :
Stringread()throwsIOException

IOException,
. 11.1 .
11.1.
// :
import java.io.*;
class MySymbInput{
public static void main(String args[]) throws IOException{
// :
char symb;
// :
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// :

System.in

303

System.out.println(" <Enter>:");
do{
// ( ):
symb=(char)br.read();
// :
System.out.println(" : "+symb);
}while(symb!='');
}}

import java.io.* java.io, -. MySymbInput


IOException. main() read() main()
. main() throws
IOException.
mian() symb char, . br
(.) :
BufferedReaderbr= newBufferedReader(newInputStreamReader(System.in))

do-while. .
symb=(char)br.read() symb. read(),
br.
,

(char).
System.out.println(" :"+symb) . , .
,
Enter:
Enter:

:
:
:
:
:
:
:
:
:
:

304

11. -

,
( ) . ,
, Enter. Enter
10.
11.2.
11.2.
import java.io.*;
class MyStringInput{
public static void main(String args[]) throws IOException{
String str=" : ";
String s;
int count=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("- ?");
s=br.readLine();
while(!s.equalsIgnoreCase("")){
count++;
str=str+"\n"+count+": "+s.toLowerCase();
System.out.println(str+"\n -?");
s=br.readLine();}
System.out.println("! !");
}}

.
:
System.out.println("-?")

. s=br.readLine()
s String. br . , ,
BufferedReaderbr=new BufferedReader(newInputStreamReader(System.in))

while !s.equalsIgnoreCase(""). , ( ),
count, ,
str . , str=str+"\
n"+count+": "+s.toLowerCase() str
- , ,
. (
), s toLowerCase().
System.out.println(str+"\n -?")

Scanner

305

s=br.readLine() .
, . :
"!!"

( ):
- ?

:
1:
-?

:
1:
2:
-?

:
1:
2:
3:
-?

:
1:
2:
3:
4:
-?

! !

, -
java.io.

Scanner
.


. JDK 5, Java
- Scanner.

306

11. -

import java.util.*, () java.util.



Scanner : System.in
Scanner, .
Scanner,
:
nextLine() ;
next() ;
nextInt() ;
nextDouble() .
Scanner 11.3.
11.3. Scanner
// :
import java.util.*;
class MyNewScanner{
public static void main(String args[]){
// Scanner System.in:
Scanner inp=new Scanner(System.in);
// ():
String name;
// ():
int age;
// :
System.out.println(" ?");
// ():
name=inp.nextLine();
// :
System.out.println(" , "+name+"!");
// :
System.out.println(" ?");
// ():
age=inp.nextInt();
// :
System.out.println(name+", "+age+" !");
}}

importjava.util.* java.util Scanner. Scanner inp=new Scanner(System.


in) System.in inp
Scanner. inp
. , .

307

name
String. age.
System.out.println(" ?")
name=inp.
nextLine(). nextLine(),
inp, name. System.out.println("
, "+name+"!") ,
. System.out.
println(" ?") . age=inp.nextInt(),
age. nextInt() inp. , System.out.println(name+",
"+age+" !")
. ( ):
?

, !
?
35
, 35 !

Scanner , ,
.


, , Swing. import
javax.swing.*. JOptionPane.
showInputDialog(), showInputDialog()
JOptionPane , . showInputDialog() ,
.
, ,
System.exit(0).

308

11. -

, showInputDialog()
, , .
. ,
parseInt() - Integer parseDouble()
- Double. . parseInt() ,
parseDouble() .
, ,
11.4.
11.4.
// :
import javax.swing.*;
class MyOptionPane{
public static void main(String args[]){
// ():
String name;
// ():
int age;
// :
System.out.println(" ?");
// :
name=JOptionPane.showInputDialog(" ");
// :
System.out.println(" : "+name);
// :
System.out.println(" , "+name+"!");
// :
System.out.println(" ?");
// :
age=Integer.parseInt(JOptionPane.showInputDialog(" "));
// :
System.out.println(" : "+age+" .");
// :
System.out.println(name+", "+age+" !");
// :
System.exit(0);}
}

, .
, .

309

Swing, import javax.swing.*


.
, name
age . ,

name=JOptionPane.showInputDialog("")

,
(.11.1).

. 11.1.

showInputDialog() ""
. (
), OK .

name.

age=Integer.parseInt(JOptionPane.showInputDialog(""))


JOptionPane.showInputDialog(" ")
Integer.parseInt()
, . .11.2.

. 11.2.


, ( System.out.println(" :

310

11. -

"+name)) ( System.out.println(" : "+age+" .")).


:
?
:
, !
?
: 35 .
, 35 !


. Swing .


,
.

. -,
.
. FileInputStream
( ) FileOutputStream ( ). FileInputStream FileOutputStream
FileNotFoundException ( ). () , ,
.
, close(). ,
, 11.5.
11.5.
// :
import java.io.*;
class WriteToFile{
public static void main(String args[]) throws IOException{
// :
int a;
try{
// :
FileOutputStream fout=new FileOutputStream("F:/Java_2/Files/mydata.txt");
// :

311

FileInputStream fin=new FileInputStream("F:/Java_2/Files/base.txt");


// :
a=fin.read();
while(a!=-1){
// :
if(a==(int)' ') a=(int)'_';
// :
fout.write(a);
// :
a=fin.read();}
// :
fout.close();
// :
fin.close();
}catch(FileNotFoundException e){ // " ":
System.out.println(" : "+e);}
// :
System.out.println(" !");}
}

: base.txt mydata.txt.
.
" !".
.
base.txt:
.
1.
2.
3.
4.

mydata.txt :
_______.
1._
2._
3.__
4.__

, . , - (
), import java.io.* java.io.
a . read(), ,
a int .

312

11. -

fout
FileOutputStreamfout=new FileOutputStream("F:/Java_2/Files/mydata.txt")

fout FileOutputStream. mydata.txt, FileOutputStream


. fout
mydata.txt.
fin
FileInputStreamfin=new FileInputStream("F:/Java_2/Files/base.txt")

fin FileInputStream.
base.txt. FileInputStream
. fin base.txt .
a=fin.read() base.
txt. fin (, ,
base.txt) read(),
. a.
while a!=-1, , , . , if(a==(int)' ') a=(int)'_' , fout.write(a)
mydata.txt.
fout ( mydata.txt) write(), . a=fin.read()
base.txt a.
while
fout.close() fin.close() . main() FileNotFoundException
( ).
. , , base.txt . :
: java.io.FileNotFoundException: F:\Java_2\Files\base.txt
( )
!

mydata.txt , -
. , , .
, mydata.txt
.

313

-, , 11.6.
11.6. -
// :
import java.io.*;
import javax.swing.*;
class FindFellow{
public static void main(String args[]) throws IOException{
// ( ):
String fileName;
// ( ):
String name;
// ( ):
String s;
// :
fileName=JOptionPane.showInputDialog(" :");
try{
// :
FileInputStream fin=new FileInputStream("F:/Java_2/Files/"+fileName);
// ( ):
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
// :
name=JOptionPane.showInputDialog(" :");
// "" :
while(true){
// :
s=br.readLine();
try{
if(s.equalsIgnoreCase(name)){// " "
System.out.println("
: "+name);
System.out.println("
: "+br.readLine());
System.out.println(" : "+br.readLine());
System.out.println("
: "+br.readLine());
System.out.println(".
: "+br.readLine());
break;}
}catch(NullPointerException e){//
System.out.println(" !");
// :
break;}
}
// :
fin.close();

314

11. -

11.6 ()
}catch(FileNotFoundException e){//
System.out.println(" : "+e);}
// :
System.exit(0);}}

,
. personal.txt, , . personal.txt :

52
526-44-12

46
526-00-13

61
522-16-48

, , , .
( )
, .
.
, : , , , .
, .
import java.io.* import javax.swing.*
java.io ( -) javax.swing (
Swing , , ).
String:
fileName , ,
name s ,
.

315


fileName= JOptionPane.showInputDialog(":")

.

FileInputStreamfin=new FileInputStream("F:/Java_2/Files/"+fileName)

fin , , .
,
fin br
BufferedReader br=newBufferedReader(newInputStreamReader(fin)).

, fin InputStream
Reader, . ,
System.in.
,
name=JOptionPane.showInputDialog(" :")

name.
while
true. s=br.readLine() . s.equalsIgnoreCase(name)
, name. ,
.
, ,
, . break, .
, ,
NullPointerException (
) , .
catch , , break .
fin.close() ,
System.exit(0) .
FileNotFound
Exception ( ).
.

316

11. -

personal.txt
(. 11.3) (. 11.4),
:

:
:
:
:
:

46
526-00-13

( ,
personal.txt),
!

,
: java.io.FileNotFoundException: F:\Java_2\Files\df
( )

.
, .

. 11.3.

. 11.4.

1. Java -.
2. InputStream
OutputStream ( read() write() -
).
3.
Reader Writer ( read() write()).

317

4. - System. , System.in.
Scanner.
5.
( Swing).
6.
. FileInputStream ( ) FileOutputStream (
).

12.

, ?

Java
AWT Swing. AWT (Abstract
Window Toolkit). Swing ,
AWT. - , ,
Java.
AWT

. ,
. : . , ,

.
Swing.
Netscape, 1996 IFC (Internet Foundation Classes). : (, , ..)
,
.
IFC Sun Microsystems Netscape
Swing, , IFC.
Swing AWT, . Swing , AWT.

319


,
.


. ,
( ).
Java :
Frame AWT JFrame Swing ( JFrame Frame). ,
, Swing
AWT
J.
. - , .
. addWindowListener() , .
AWT Swing, javax.swing ( Swing), java.awt java.awt.
event ( AWT). , AWT , 12.1.
12.1. AWT
// AWT:
import java.awt.*;
import java.awt.event.*;
// :
class MyAdapter extends WindowAdapter{
public void windowClosing(WindowEvent we){
System.exit(0);}
}
// :
class JustAFrame extends Frame{
// :
JustAFrame(int a,int b){
// - :
super(" ");
// :
MyAdapter adapter=new MyAdapter();
// :
setSize(a,b);

320

12.

12.1 ()
// :
setVisible(true);
// :
addWindowListener(adapter);}
}
class MyAWTFrame{
public static void main(String args[]){
// :
JustAFrame frame=new JustAFrame(400,300);
}}

AWT,
:
MyAdapter, () JustAFrame, MyAWTFrame ,
(). ,
, .12.1.

. 12.1.

, ,
( , , -, )
.
, (
) .

JustAFrame, Frame AWT.
,
.
super("") , . setSize(a,b) Frame setSize() ( )
.

321

,
setVisible(true) ( ).
, Frame setVisible(),
true .
MyAdapter adapter=new MyAdapter() , adapter MyAdapter. addWindow
Listener(adapter) , adapter , . ,
, MyAdapter. windowClosing(), WindowAdapter.
(
). windowClosing() .
System.exit(0) ,
( ).
, Java , . , . ,
-.
, , ,
. ,
- . adapter,
JustAFrame, . addWindowListener()
, ( ), , .
. ,
, (,
), .
, -,
MyAdapter adapter=new MyAdapter() addWindowListener(adapter)
addWindowListener(new MyAdapter()).
. MyAdapter , JustAFrame MyAdapter adapter=new MyAdapter()
addWindowListener(adapter) ,
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});

322

12.

addWindowListener() ( WindowAdapter), windowClosing().


frame JustAFrame
JustAFrameframe=newJustAFrame(400,300)

,
400 300 , .12.1.
Swing.
12.2.
12.2. Swing
// :
import javax.swing.*;
// JFrame:
class JustAFrame extends JFrame{
// :
public JustAFrame(int a,int b){
// - :
super(" ");
// :
setSize(a,b);
// :
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// :
setVisible(true);}
}
class MyFrame{
public static void main(String args[]){
// :
JustAFrame frame=new JustAFrame(300,200);
}}

JustAFrame JFrame Swing.


,
.
, 12.1, :
setSize() , setVisible()
. .
.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

setDefaultCloseOperation(), , EXIT_ON_CLOSE
JFrame, , .

323

JustAFrame
frame=new JustAFrame(300,200), 300 200
( ).
.12.2.

. 12.2. Swing

, .12.1 12.2 (
). , , Swing, .


- ?
. .


, , .

. , , , , ..
, , .
Java (
, ,
). . , .
, Java , AWT. , ( Swing)
( AWT) ,
.
, , EventObject,
java.util Java

324

12.

Object. , EventObject
AWTEvent. AWT , , java.awt.
AWT AWTEvent java.awt.event.
AWT . 12.3.

. 12.3.

( AWT) .12.1.
12.1. AWT

ActionEvent


Button, List

TextField

AdjustmentEvent


Scrollbar

ComponentEvent


, ,

ItemEvent


Checkbox, Choice

List

TextEvent

TextComponent,
TextArea TextField

325

ContainerEvent


Container, Dialog,
FileDialog, Frame, Panel,
ScrollPane Window

FocusEvent

InputEvent

,
KeyEvent MouseEvent.

PaintEvent

WindowEvent

,
, , Dialog, FileDialog,
,
Frame Window

KeyEvent

, ,

MouseEvent


,
, ,


..

, Java,
. ,
, , (, , ),
. . ,
.
.12.1 . . ,
.
, ,
. . , Event

326

12.

Listener. , WindowEvent WindowListener.


InputEvent .
, , .
. , , ,
. .
, , . add,
( Event) , , Listener.
, WindowEvent addWindowListener(). .
. .



, , , . . 12.3.
12.3. Swing
// :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
// :
class MyFrame extends JFrame{
// :
public static int count=0;
// :
MyFrame(int a,int b){
count++; //
// :
setTitle(" : "+count);

327

// :
MyPanel panel=new MyPanel();
setSize(300,200); //
// :
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(a,b); //
add(panel);
//
setVisible(true); //
}}
// :
class MyPanel extends JPanel{
// :
MyPanel(){
// :
JButton button=new JButton(" ");
add(button);
//
button.addActionListener(listener);} //
// - :
ActionListener listener=new ActionListener(){
public void actionPerformed(ActionEvent event){
Random rnd=new Random();
// :
MyFrame frame=new MyFrame(rnd.nextInt(800),rnd.nextInt(500));}};
}
class FrameAndButton{
public static void main(String args[]){
// :
MyFrame frame=new MyFrame(100,100);}
}

: :1, .12.4.

. 12.4. ,

.
. . .

328

12.


( ),
. .
, .
.12.5.

. 12.5.

MyFrame JFrame.
count .
.
, .
count ( count++ ), setTitle()
:
count. . ,
, MyPanel panel=new MyPanel()
panel MyPanel ( ).
add(panel),
add(), . ,
add().

329

setSize(300,200),
setLocation(a,b) ( a b
). , ,
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

setVisible(true).
. . , .
MyPanel JPanel Swing. . button (
JButton Swing)
JButtonbutton=newJButton("")

JButton. add(button). button.


addActionListener(listener)
listener , ActionListener.
actionPerformed(), ,
.
FrameAndButton
MyFrameframe=newMyFrame(100,100)

,
12.4.
12.4. AWT
// :
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
// :
class MyFrame extends Frame{
public static int count=0; //
// :
MyFrame(int a,int b){
count++;
//
setTitle(" : "+count);
setLayout(null);
//
Font f=new Font("Arial",Font.BOLD,11); //
setFont(f);
//
Button btn=new Button(" ");
btn.setBounds(50,100,200,30); //
add(btn);
//
setBounds(a,b,300,200);
//

330

12.

12.4 ()
// :
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ve){
System.exit(0);}
//
});
// :
btn.addActionListener(new ButtonPressed());
setVisible(true);
//
}}
// :
class ButtonPressed implements ActionListener{
private Random rnd;
// :
ButtonPressed(){
rnd = new Random();}
public void actionPerformed(ActionEvent ae){
// :
new MyFrame(rnd.nextInt(800),rnd.nextInt(500));}
}
class FrameAndButtonAWT{
public static void main(String args[]){
// :
MyFrame frame=new MyFrame(100,100);}
}

AWT. , Frame AWT


, , MyFrame.
count ( ). , .
count++ count,
setTitle(":"+count)
( MyFrame). setLayout(null) : (,
) .
, . Font f=new Font("Arial",Font.BOLD,11) f, Arial 11 . setFont(f). Button btn=new Button("
") btn ( Button
AWT), btn.setBounds(50,100,200,30)
( 50
100 )

331

(200 30 ).
add(btn).
setBounds(a,b,300,200). a b (
) (
),
300 , 200 .
( )
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ve){
System.exit(0);}
});

, setVisible(true), .
, ,

btn.addActionListener(newButtonPressed())

ButtonPressed. ButtonPressed ActionListener. rnd


Random ( ), actionPerformed().
Random, rnd.
actionPerformed() new MyFrame(rnd.nextInt(800),rnd.nextInt(500)) MyFrame,
. ( ) 0 800, 0 500.
, . .
FrameAndButtonAWT MyFrame
frame=new MyFrame(100,100) (, ).
.12.6.

. 12.6. ,

332

12.

.12.7 , .

. 12.7.

, (),
. ,
.


, .

, .
.12.8 Java AWT.

333

. 12.8. AWT

.12.2.
12.2. AWT

Button

: Button() , Button()
. : getLabel() ,
setLabel() .
: ComponentEvent ( , ,
), FocusEvent ( ), KeyEvent (
), MouseEvent (
), ActionEvent
( )

Checkbox


( )
( )

: Checkbox() , Checkbox() , Checkbox(,


)
( true false). : getLabel()
()

334

12.

12.2 ()

, setLabel() , getState() , setState()


. : ItemEvent
( ), ComponentEvent, FocusEvent, KeyEvent
MouseEvent

Checkbox

()

CheckboxGroup

- : CheckboxGroup()
( ). ,
CheckboxGroup, CheckboxGroup(, , )
CheckboxGroup(, , )
.
(), () .
, true.
: getSelectedCheckbox() () ,
setSelectedCheckbox()
( )

Choice

: Choice()
. : add() (

), insert(,)
, select()
select() ,
remove() remove() , removeAll()
, getItem()
, getSelectedIndex()
,
getSelectedItem() , getItemCount()
. : ItemEvent
( ),
ComponentEvent, FocusEvent, KeyEvent MouseEvent

List

: List() , List()
,
List(,)

List


( true, ).
: add() ,
add(,) ,
remove() remove() , removeAll()
, getItem()
, getSelectedIndex()
,
getSelectedItem() , getSelectedIndexes() () ,
getSelectedItems() ()
, getItemCount() . :
ActionEvent (
), ComponentEvent,
FocusEvent, KeyEvent MouseEvent

()

TextComponent

335

(
). :
getText() ,
setEditable() ,

, isEditable() ,
, getCaretPosition()
, setCaretPosition() ,
select(,) ,
selectAll()
, setSelectionStart() ,
setSelectionEnd()
, getSelectedText()
,
getSelectionStart()
, getSelectionEnd()
.
: TextEvent ( ), ComponentEvent, FocusEvent,
KeyEvent MouseEvent

336

12.

12.2 ()

TextField


( )

TextComponent.
: TextField()
, TextField() ,
TextField() ,
TextField(,) .
: getColumns() , setColumns()
, setEchoChar() , echoCharIsSet() ,
,
getEchoChar() , setEchoChar(0)
. :
ActionEvent (
Enter), TextEvent ( ), ComponentEvent, FocusEvent, KeyEvent
MouseEvent

TextArea


( )

TextComponent.
: TextArea(,,
,)
(:
SCROLLBARS_NONE, SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY, SCROLLBARS_BOTH).
.
: append()
, insert(,)
, replaceRange(,
,)
. : TextEvent (
), ComponentEvent,
FocusEvent, KeyEvent MouseEvent

Scrollbar

: Scrollbar() ( )

0 100
0, Scrollbar()
(HORIZONTAL VERTICAL) (
), Scrollbar(, ,
,,) , ( ),

337

. : getValue() . :
AdjustmentEvent (
), ComponentEvent, FocusEvent,
KeyEvent MouseEvent

Scrollbar

()

Panel

()

: Panel()
FlowLayout, Panel()

ScrollPane

: ScrollPane()
, ScrollPane()

SCROLLBARS_ALWAYS
( ), SCROLLBARS_AS_NEEDED
( ) SCROLLBARS_NEVER (). : getHAdjustable()
, getVAdjustable()
, getScrollPosition()
Point ,
, setScrollPosition()
setScrollPosition(x,y) x y.
Point

Window

: Window() ,
( Window
Frame). : show() , hide() ,
isShowing() , ,
toFront()
, toBack()
, dispose() . :
WindowEvent ( , ,
), ComponentEvent, FocusEvent,
KeyEvent MouseEvent

338

12.

12.2 ()

Frame

: Frame()
, Frame() . :
setTitle() ,
setMenuBar()
( MenuBar), setIconImage()
( Image). :
WindowEvent ( ,
,
), ComponentEvent, FocusEvent,
KeyEvent MouseEvent

Dialog

: Dialog(,
,) false
, (
, ) ( Dialog Frame).
.
: isModal()
, setModal()
. :
WindowEvent ( ,
,
), ComponentEvent, FocusEvent,
KeyEvent MouseEvent

FileDialog

: FileDialog(,
,)
, ( Frame)
(
FileDialog.LOAD )
(
FileDialog.SAVE) . . :
getDirectory()
, getFile()
, setDirectory()
, setFile()
. : WindowEvent
( ,
,
), ComponentEvent, FocusEvent, KeyEvent
MouseEvent

Canvas


Canvas() paint().

339

Swing .12.3.
12.3. Swing

AbstractButton

- Swing

ButtonGroup

ImageIcon

().

url-

JApplet

. Applet

JButton

JCheckBox

JComboBox

JLabel

JRadioButton

JScrollPane

JTabbedPane

JTable

JTextField

JTree

AWT
.


, .

,
. x
y( x ) =

1 + sin( x)
.
1+ | x |

, .

340

12.

0 1, .
. , 12.5.
12.5.
// :
import java.awt.*;
import java.awt.event.*;
// :
class PlotFrame extends Frame{
// ( - ):
PlotFrame(int H,int W){
// :
setTitle(" ");
setBounds(100,50,W,H);
//
setBackground(Color.GRAY);
//
setLayout(null);
//
Font f=new Font("Arial",Font.BOLD,11); //
setFont(f);
//
BPanel BPnl=new BPanel(6,25,W/4,H-30);
//
add(BPnl);
//
// ():
PPanel PPnl=new PPanel(W/4+10,25,3*W/4-15,H-120,BPnl);
// :
add(PPnl);
// :
HPanel HPnl=new HPanel(W/4+10,H-90,3*W/4-15,85);
// :
add(HPnl);
// ( ):
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ve){
System.exit(0);}
//
});
// :
BPnl.B1.addActionListener(new Button1Pressed(BPnl,PPnl));
// :
BPnl.B2.addActionListener(new Button2Pressed());
// :
BPnl.Cb[3].addItemListener(new cbChanged(BPnl));
// () :
setResizable(false);
// :
setIconImage(getToolkit().getImage("C:/icons/icon.png"));

341

setVisible(true);
//
}}
// :
class BPanel extends Panel{
// :
public Label[] L;
// :
public CheckboxGroup CbG;
// :
public Checkbox[] Cb;
// :
public Choice Ch;
// :
public TextField TF;
// :
public Button B1,B2;
//
// ( - ):
BPanel(int x,int y,int W,int H){
// :
setLayout(null);
setBounds(x,y,W,H);
//
setBackground(Color.LIGHT_GRAY);
//
// :
L=new Label[3];
// :
L[0]=new Label(" :",Label.CENTER);
// :
L[0].setFont(new Font("Arial",Font.BOLD,12));
// :
L[0].setBounds(5,5,getWidth()-10,30);
// :
add(L[0]);
// :
CbG=new CheckboxGroup();
Cb=new Checkbox[4];
// :
Cb[0]=new Checkbox(" ",CbG,true); //
Cb[1]=new Checkbox(" ",CbG,false); //
Cb[2]=new Checkbox(" ",CbG,false); //
// :
Cb[3]=new Checkbox(" ",true);
// :
for(int i=0;i<4;i++){
Cb[i].setBounds(5,30+i*25,getWidth()-10,30); //
add(Cb[i]);

342

12.

12.5 ()
}
// :
Ch=new Choice();
// "":
Ch.add("");
// "":
Ch.add("");
// "":
Ch.add("");
// :
Ch.setBounds(20,140,getWidth()-25,30);
// :
add(Ch);
// :
L[1]=new Label(" :",Label.CENTER);
// :
L[1].setFont(new Font("Arial",Font.BOLD,12));
// :
L[1].setBounds(5,220,getWidth()-10,30);
// :
add(L[1]);
// :
L[2]=new Label(" x=0 x=",Label.LEFT);
// :
L[2].setBounds(5,250,70,20);
// :
add(L[2]);
// :
TF=new TextField("10");
// :
TF.setBounds(75,250,45,20);
// :
add(TF);
// (""):
B1=new Button("");
// (""):
B2=new Button("");
// :
B1.setBounds(5,getHeight()-75,getWidth()-10,30);
// :
B2.setBounds(5,getHeight()-35,getWidth()-10,30);
add(B1);
//
add(B2);
//
}}
// :
class PPanel extends Panel{

343

// :
public Plotter G;
// :
class Plotter{
// :
private double Xmin=0,Xmax,Ymin=0,Ymax=1.0;
// :
private boolean status;
// :
private Color clr;
// :
private Color gclr;
//
// ( - ):
Plotter(BPanel P){
// :
try{
Xmax=Double.valueOf(P.TF.getText());}
catch(NumberFormatException e){
P.TF.setText("10");
Xmax=10;}
status=P.Cb[3].getState();
// :
switch(P.Ch.getSelectedIndex()){
case 0:
gclr=Color.GREEN;
break;
case 1:
gclr=Color.YELLOW;
break;
default:
gclr=Color.GRAY;}
// :
String name=P.CbG.getSelectedCheckbox().getLabel();
if(name.equalsIgnoreCase(" ")) clr=Color.RED;
else if(name.equalsIgnoreCase(" ")) clr=Color.BLUE;
else clr=Color.BLACK;
}
// :
private double f(double x){
return (1+Math.sin(x))/(1+Math.abs(x));}
// :
public Plotter remember(BPanel P){
return new Plotter(P);}
//
// (Fig - ):

344

12.

12.5 ()
public void plot(Graphics Fig){
// :
int H,W,h,w,s=20;
H=getHeight();
W=getWidth();
h=H-2*s;
w=W-2*s;
// :
Fig.clearRect(0,0,W,H);
// :
int k,nums=10;
// - :
Fig.setColor(Color.BLACK);
// :
Fig.drawLine(s,s,s,h+s);
Fig.drawLine(s,s+h,s+w,s+h);
// :
for(k=0;k<=nums;k++){
Fig.drawLine(s+k*w/nums,s+h,s+k*w/nums,s+h+5);
Fig.drawLine(s-5,s+k*h/nums,s,s+k*h/nums);
Fig.drawString(Double.toString(Xmin+k*(Xmax-Xmin)/nums),s+k*w/nums-5,s+h+15);
Fig.drawString(Double.toString(Ymin+k*(Ymax-Ymin)/nums),s-17,s+h-1-k*h/nums);
}
// ( ):
if(status){
Fig.setColor(gclr);
// :
for(k=1;k<=nums;k++){
Fig.drawLine(s+k*w/nums,s,s+k*w/nums,h+s);
Fig.drawLine(s,s+(k-1)*h/nums,s+w,s+(k-1)*h/nums);
}}
// :
Fig.setColor(clr);
//
// :
double dx=(Xmax-Xmin)/w,dy=(Ymax-Ymin)/h;
// :
double x1,x2,y1,y2;
// :
int h1,h2,w1,w2;
// :
x1=Xmin;
y1=f(x1);
w1=s;
h1=h+s-(int)Math.round(y1/dy);
// :
int step=5;

345

// :
for(int i=step;i<=w;i+=step){
x2=i*dx;
y2=f(x2);
w2=s+(int)Math.round(x2/dx);
h2=h+s-(int)Math.round(y2/dy);
// :
Fig.drawLine(w1,h1,w2,h2);
// ():
Fig.drawRect(w1-2,h1-2,4,4);
// :
x1=x2;
y1=y2;
w1=w2;
h1=h2;}
}}
//
// ( - ,
// ):
PPanel(int x,int y,int W,int H,BPanel P){
// :
G=new Plotter(P);
// :
setBackground(Color.WHITE);
// :
setBounds(x,y,W,H);
}
// :
public void paint(Graphics g){
//
// :
G.plot(g);
}}
// :
class HPanel extends Panel{
// :
public Label L;
// :
public TextArea TA;
//
// ( - ):
HPanel(int x,int y,int W,int H){
// :
setBackground(Color.LIGHT_GRAY);
// :
setBounds(x,y,W,H);

346

12.

12.5 ()
// :
setLayout(null);
// :
L=new Label("",Label.CENTER);
// :
L.setBounds(0,0,W,20);
// :
add(L);
// :
TA=new TextArea(" y(x)=(1+sin(x))/(1+|x|)");
// :
TA.setFont(new Font("Serif",Font.PLAIN,15));
// :
TA.setBounds(5,20,W-10,60);
// :
TA.setEditable(false);
// :
add(TA);
}}
// :
class Button1Pressed implements ActionListener{
// :
private BPanel P1;
// :
private PPanel P2;
// ( - ):
Button1Pressed(BPanel P1,PPanel P2){
this.P1=P1;
this.P2=P2;}
// :
public void actionPerformed(ActionEvent ae){
// () :
P2.G=P2.G.remember(P1);
// ( ):
P2.G.plot(P2.getGraphics());
}}
// :
class Button2Pressed implements ActionListener{
// :
public void actionPerformed(ActionEvent ae){
// :
System.exit(0);
}}
// :
class cbChanged implements ItemListener{

347

// :
private Choice ch;
// ( - ):
cbChanged(BPanel P){
this.ch=P.Ch;}
// :
public void itemStateChanged(ItemEvent ie){
// :
ch.setEnabled(ie.getStateChange()==ie.SELECTED);
}}
// :
class PlotDemo{
public static void main(String args[]){
// :
new PlotFrame(400,500);}
}

,
.12.9.

. 12.9.

,
, , . ,
, .
. : , (,

348

12.

).
( Panel).
,
( ). , , (, ),
.
,
. , .
, .
. 10.
, .
.12.10
0 30.

. 12.10.

, .
, (.12.5). , . : PlotFrame
,
( : BPanel,
PPanel HPanel), Button1Pressed
, Button2Pressed

349

, cbChanged
, Plotter ( PPanel) ,
PlotDemo .
BPanel Panel .
L, CbG,
Cb Checkbox (
CbG, ), Ch,
TF B1 B2. . (
,
), . , .
, .
BPanel setLayout(null) .
setBounds(x,y,W,H). setBounds() . setBackground(Color.LIGHT_
GRAY). LIGHT_GRAY Color (-).
L=newLabel[3] , L .
, L .
. , , L[0]=new Label("
:",Label.CENTER) . " :", (
CENTER Label). L[0].setFont(new Font("Arial",Font.BOLD,12)).
setFont() Font, new Font("Arial",Font.BOLD,12).
L[0].setBounds(5,5,getWidth()-10,30). getWidth() . , add(L[0]) . ,
.
CbG=new CheckboxGroup().
Cb=new Checkbox[4]
Checkbox.
, .
:
Cb[0]=new Checkbox("",CbG,true)
Cb[1]=new Checkbox("",CbG,false)
Cb[2]=newCheckbox("",CbG,false).

350

12.

Checkbox() , , , (true, ,
false, ). , , . Cb[3]=new Checkbox(" ",true).
,
( ). .
, ,
.
Ch=new Choice(). . Ch.add(""), Ch.add("") Ch.add("").
. ( )
Ch.setBounds(20,140,getWidth()-25,30). 20
140 . 30 , 25 . add(Ch).
L[1] L[2] ( " x"
"x=0 x="). ,
, ,
.
TF=new TextField("10"). TextField "10".
.
TF.setBounds(75,250,45,20) ( 45 20 75 250
),
add(TF).
, ( Button) B1=new
Button("") B2=new Button(""). Button.
setBounds(), add().
HPanel . Panel ( Label L) ( TextArea TA).
. , . ,
TA.setEditable(false) ,
. , ( ) . ,

351

,
. .
PPanel . Panel.
G Plotter. ,
.
, .
double: Xmin ( 0), Xmax, Ymin ( 0) Ymax
( 1.0).
. . Xmax
.
status , . clr gclr Color
.
Plotter BPanel, , . , , .

. ,
( ) .
try. Xmax=Double.
valueOf(P.TF.getText()) Xmax:
getText() TF P , valueOf() - Double double.
( NumberFormatException).
catch. , P.TF.setText("10")
10. Xmax=10 Xmax.
status status=P.Cb[3].getState().
getState() Cb[3] (,
, P). status
true, , false, .
P.Ch.getSelectedIndex()
Ch. switch()
.
. 0 ( Color.GREEN), 1 ( Color.
YELLOW), 2 ( Color.GRAY).
gclr.

352

12.

. String name=P.CbG.
getSelectedCheckbox().getLabel() name . CbG
getSelectedCheckbox(). getLabel(),
. ,
clr (Color.RED, Color.BLUE Color.
BLACK).
Plotter f() double.
, .
remember() BPanel , , . , ,
.

plot() Plotter.
Fig Graphics. ,
. ( )
getGraphics() .
H=getHeight() W=getWidth() , . h=H-2*s w=W-2*s
( s
).
Fig.clearRect(0,0,W,H) . , . ,
.
. Fig.setColor
(Color.BLACK) , Fig.drawLine
(s,s,s,h+s) Fig.drawLine(s,s+h,s+w,s+h) . (, )
drawLine(), -

. . drawString().
.
toString() Double.
nums .

353

( status true),
. Fig.setColor(gclr)
, .
( Fig.
setColor(clr)). . ( ) step.
, .
drawRect(), ( ).
Plotter .
- PPanel , ( ), P BPanel ( ). G=newPlotter(P)
Plotter G.
setBackground(Color.WHITE).
setBounds(), .
PPanel paint().
, . ,
. .
, G.plot(g) ( g paint(), ), .
PlotFrame Frame.
W H . , . , setTitle(" ") ( ). setBounds(100,50,W,H).
setBackground(Color.GRAY),
setLayout(null).
Font f=new Font("Arial",Font.BOLD,11) ( f Font),
setFont(f). ( ) .
BPanel BPnl=new BPanel(6,25,W/4,H-30).
add(BPnl). PPanel PPnl=new PPanel(W/4+10,25,3*W/4-15,H120,BPnl), add(PPnl).
HPanel HPnl=new HPanel(W/4+10,H-90,3*W/4-15,85), add(HPnl).

354

12.

, :
, ,
. , addWindowListener() ( ).
BPnl.
B1.addAction
Listener(new Button1Pressed(BPnl,PPnl)), BPnl.B2.addActionListener(new Button2Pressed()),
BPnl.Cb[3].addItemListener(new
cbChanged(BPnl)). . .
, setResizable(false).

setIconImage(getToolkit().getImage("C:/icons/icon.png"))

setIconImage() ( Image). getImage().


(), Toolkit, getToolkit().
, setVisible(true).
Button1Pressed ActionListener. -: P1 (
BPanel) P2 ( PPanel).
. .
actionPerformed()
P2.G=P2.G.remember(P1) P2.G.plot(P2.getGraphics()). G, P2.
remember(),
G
.
Button2Pressed
ActionListener.
actionPerformed(), System.exit(0),
(, , ).
,
( ),
. ItemListener cbChanged
. ch Choice
( ) ,

355

. , .
ch.
cbChanged
itemStateChanged().
ch.setEnabled(ie.getStateChange()==ie.SELECTED)

SELECTED ( ). getStateChange() SELECTED, , DESELECTED, . ,


ie ItemEvent.
setEnabled(), ch, ()
, . ,
.
PlotDemo new PlotFrame(400,500)
. PlotFrame() .
,
, ,
. , . , , .
. .
, ,
.

?
.


Swing
. -.
, .
12.6.

356

12.

12.6.
// :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// :
class CalculatorFrame extends JFrame{
// :
CalculatorFrame(){
// :
int w=270,h=240;
// :
setTitle("");
// :
setBounds(100,100,w,h);
// :
CPanel panel=new CPanel(w,h);
// :
add(panel);
// :
setResizable(false);
// :
setVisible(true);
// :
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
// :
class CPanel extends JPanel{
// :
public JTextField TF;
// :
private BtnAction BtnPressed;
// ( - ):
CPanel(int W,int H){
// :
int w=W/5,h=H/8,sx=w/5,sy=h/3;
// :
setLayout(null);
// :
setBounds(0,0,W,H);
// :
JTextField TF=new JTextField();
// :
TF.setHorizontalAlignment(JTextField.RIGHT);
// :
TF.setBounds(sx,sy,2*sx+3*w,h);
// :

357

TF.setEditable(false);
// :
add(TF);
// :
BtnPressed=new BtnAction(TF);
// :
String[] BtnTxt={"1","2","3","+","4","5","6","","7","8","9","/","0",".","=","*"};
// :
for(int i=0;i<BtnTxt.length;i++){
addBtn(sx+(w+sx)*(i%4),(2*sy+h)+(sy+h)*(i/4),w,h,BtnTxt[i],BtnPressed);}
// :
JButton BtnC=new JButton("C");
// :
BtnC.setBounds(4*sx+3*w,sy,w,h);
// :
BtnC.addActionListener(BtnPressed);
// :
BtnC.setFocusPainted(false);
// :
BtnC.setForeground(Color.RED);
// :
add(BtnC);}
//
// ( - , ):
void addBtn(int i,int j,int w,int h,String txt,ActionListener AcList){
// :
JButton b=new JButton(txt);
// :
b.setBounds(i,j,w,h);
// :
b.setFocusPainted(false);
// :
b.addActionListener(AcList);
// :
add(b);}
}
// :
class BtnAction implements ActionListener{
// :
public JTextField TF;
// :
private boolean start;
// :
private boolean point;
// :

358

12.

12.6 ()
private String cmnd;
// :
private double result;
// :
private void onStart(){
start=true;
point=true;
cmnd="C";
result=0;
TF.setText("0.0");}
// :
private void calc(){
// :
double x;
x=Double.parseDouble(TF.getText());
// :
if(cmnd.equals("*")) result*=x;
else if(cmnd.equals("/")) result/=x;
else if(cmnd.equals("-")) result-=x;
else if(cmnd.equals("+")) result+=x;
else result=x;
// :
TF.setText(Double.toString(result));}
// ( - ):
BtnAction(JTextField TF){
this.TF=TF;
onStart();}
// :
public void actionPerformed(ActionEvent ae){
// :
String str=ae.getActionCommand();
// :
if(str.equals("C")){//
onStart();
return;}
// :
if(str.equals("+")|str.equals("-")|str.equals("*")|str.equals("/")|str.
equals("=")){
calc();
cmnd=str;
start=true;
point=true;
return;}
// :
if(start){//
if(str.equals(".")){//

359

TF.setText("0.");
point=false;
start=false;
return;}
else{//
TF.setText(str);
start=false;
return;}
}
else{//
if(str.equals(".")){//
str=point?str:"";
point=false;}
// :
// :
if(TF.getText().equals("0")&!str.equals(".")) TF.setText(str);
else TF.setText(TF.getText()+str);}
}}
// :
class MyCalculator{
public static void main(String[] args){
// :
new CalculatorFrame();
}}

.12.11 .

. 12.11. -

, , , , .

, .
,
.
.

360

12.

CalculatorFrame,
JFrame Swing. , , , setTitle("") . setBounds(). CPanel (,
, JPanel). add() . setResizable(false)
, setVisible(true).
, setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
CPanel, . ,
JPanel Swing. CPanel
: TF JTextField ( ) BtnPressed BtnAction (
). , 17 , ,
BtnPressed. BtnAction .
.
setLayout(null) ( ).
,
setBounds() ( ). JTextField TF=new JTextField() TF.
.
, TF.setHorizontalAlignment(JTextField.RIGHT).
setBounds(), TF.
TF.setEditable(false)
( ). add(TF).
BtnPressed=new
BtnAction(TF).
BtnPressed. BtnAction
TF.

(.).
String[] BtnTxt={"1","2","3","+","4","5","6","-","7","8","9","/","0",
".","=","*"}
( , ). i,
0 BtnTxt.length-1 . addBtn() ( .), , ,

361

, . ,
. ,
-
, .
,
JButton BtnC=new JButton("C"). BtnC ,
. ,
.
BtnC setBounds().
BtnC.addActionListener(BtnPressed). , BtnC.
setFocusPainted(false) . ,

BtnC.setForeground(Color.RED). ,
add(BtnC).
addBtn() CPanel
. JButton b=new
JButton(txt), JButton addBtn(). b.setBounds(i,j,w,h),
addBtn(). b.setFocusPainted(false).
b.addActionListener(AcList) ( addBtn()). , , , , , addBtn().
. add(b).
, , ,
, .
.
BtnAction, ActionListener. , ,
JTextFieldTF . ,
start, TF, point,
, cmnd, , double result,
.
. onStart(), : start
point true, cmnd "C", result, TF.setText("0.0")
"0.0".

362

12.

calc() .
x=Double.parseDouble(TF.getText()) , double
x. , cmnd, .
, ,
x, . result. , calc()
. , cmnd,
, x.
,
result.
TF.setText(Double.toString(result))
. result
toString(), Double.
BtnAction ,
TF. onStart(),
.
BtnAction actionPerformed(), . String str=ae.
getActionCommand() ,
. ( ) str. . , (
str.equals("C")), onStart()
actionPerformed() ( return).
(
str.equals("+")|str.equals("-")|str.equals("*")|str.equals("/")|str.equals("=")),
calc() ( ),
cmnd=str cmnd, start point true, . true start , , point
.
(
) . start. ,
( start), ,
( str.equals(".")) TF
"0." ( ). point start
false, ( return). ( str.equals(".") ),
TF TF.setText(str), start=false
return.

363

start ( start
actionPerformed() false) , TF.
str str=point?str:"" point=false.
str (
"."), . .
,
. , , : , .
TF. , .
TF.getText().equals("0")&!str.equals("."), , TF , . , TF.setText(str).
(, , ). ,
, TF.setText(TF.getText()+str),
.
MyCalculator new
CalculatorFrame(), .

,
main(). Java . Java . , ,
,
.
, , .
main(). . .
init(). . Applet.
,
Applet. , init(),
destroy(), , start(),
, stop(),
, .
.

364

12.

-. , ,
, .
(HTML-). , ,
, ,
( ) . HTML <applet>.
code
( class). HTML- <applet> 12.7.
12.7. HTML-
<html>
<head><title> </title></head>
<body>
:<br>
<applet code="ShowStringApplet.class" width="100%" height="100">
</applet>
</body>
</html>

ShowStringApplet.html, ,
ShowStringApplet.class, Java- ShowString
Applet.java, 12.8.
12.8.
import java.applet.*;
import java.awt.*;
public class ShowStringApplet extends Applet{
public void paint(Graphics g){
g.drawString(" !",10,50);
}}

HTML- ,
,
HTML-.
, . .
. , HTML- <html> </html>. HTML-
. HTML-. ,
<head> </head>. , <title> </title>.
<body> </body>.

365

.
, .
: ( ). , <applet>
code="ShowStringApplet.class" ( ), width="100%" ( 100%
) height="100" ( 100 ).
:,
<br> ( ). , . .
ShowStringApplet.html , , .12.12.

. 12.12.

12.8. import java.applet.* . AWT import java.awt.*.


paint(). . paint() drawString(),
, , ,
( ). drawString()
, paint().
, ( , ), , .12.13.
12.9.

366

12.

12.9.
import java.applet.*;
import java.awt.*;
public class ShowStringApplet extends Applet{
public void init(){
setBackground(Color.YELLOW);
setFont(new Font("Serief",Font.BOLD,18));
}
public void paint(Graphics g){
g.drawString(" !",10,50);
}}

. 12.13.

init().
setBackground(Color.YELLOW)
. , setFont(new Font("Serief",Font.BOLD,18)) .
, .

. 12.10 ,
,
.
12.10.
// :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
// :

367

public class MyApplet extends Applet{


// :
private Label L;
// :
private Button BtnH;
private Button BtnL;
// :
private String txt=" : ";
// :
private int size;
// :
private BtnPressed BP;
// :
public void init(){
// :
setBackground(Color.WHITE);
// :
size=20;
// :
int W,H;
// :
W=getWidth();
// :
H=2*getHeight()/3;
// :
setLayout(null);
// :
L=new Label();
// :
L.setAlignment(Label.CENTER);
// ():
L.setSize(W,H);
// :
L.setLocation(0,0);
// :
L.setBackground(Color.WHITE);
// :
L.setFont(new Font("Serief",Font.BOLD,size));
// :
L.setText(txt+L.getFont().getSize());
// ():
BtnH=new Button(" >>");
// ():
BtnL=new Button("<< ");
// :
BtnH.setBounds(W/4,H+1,W/4,H/4);

368

12.

12.10 ()
// :
BtnL.setBounds(W/2+1,H+1,W/4,H/4);
// :
BtnH.setFont(new Font("Arial",Font.BOLD,11));
// :
BtnL.setFont(new Font("Arial",Font.BOLD,11));
// :
BP=new BtnPressed();
// :
BtnH.addActionListener(BP);
// :
BtnL.addActionListener(BP);
// :
add(BtnH);
// :
add(BtnL);
// :
add(L);}
// :
class BtnPressed implements ActionListener{
// , :
private void pressed(boolean btn){
if(btn) size++;
else size--;
L.setFont(new Font("Serief",Font.BOLD,size));
L.setText(txt+L.getFont().getSize());
if(size>15) BtnL.setEnabled(true);
else BtnL.setEnabled(false);
if(size<25) BtnH.setEnabled(true);
else BtnH.setEnabled(false);}
// :
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==BtnH) pressed(true);
if(ae.getSource()==BtnL) pressed(false);}
}}

HTML- 12.11.
12.11. HTML-
<html>
<head><title> </title></head>
<body>
. :<br>
<applet code="MyApplet.class" width="600" height="200">
</applet>
</body>
</html>

369

HTML- .12.14.

. 12.14. ,

20 .
>> ,
<< .
.
25 15. ,
, . 12.15.

. 12.15.

370

12.

.
MyApplet Applet, ,
init()
BtnPressed. ( ): L ( Label),
BtnH BtnL ( Button), txt ( String), ( int) size, , BP
( BtnPressed).
init() setBackground(Color.WHITE)
, size=20 , . W=getWidth() H=2*getHeight()/3
( ).
, HTML (.12.11). , , setLayout(null).
L=newLabel(),
L. , L.setAlignment(Label.CENTER).
L.setSize(W,H) L.setLocation(0,0)
.
L.setBackground(Color.WHITE).
L.setFont(new Font("Serief",Font.BOLD,size)),
size.
. L.setText(txt+L.getFont().getSize())
L.getFont() (
Font). getSize(),
. , , txt,
. .
BtnH=new Button(" >>"), BtnL=new Button("<< "). BtnH.setBounds(W/4,H+1,W/4,H/4) BtnL.
setBounds(W/2+1,H+1,W/4,H/4). ,
, BtnH.setFont(new Font("Arial",Font.BOLD,11)) BtnL.
setFont(new Font("Arial",Font.BOLD,11)).
BP=new BtnPressed() (
BtnPressed, ),
( BtnH.addAction
Listener(BP) BtnL.addActionListener(BP)).
add(BtnH), add(BtnL) add(L).
BtnPressed ActionListener. .

371

pressed() , , .
true
, false
. , , . size
L.setFont(new Font("Serief",Font.BOLD,size)) L.setText(txt+L.getFont().getSize()) . ,
. , :
15,
(
), 25,
(
). , pressed() , .
BtnPressed actionPerformed(), ,
, . . getSource(), , , (
ActionEvent). BtnH, pressed()
true. BtnL, pressed() false.
JApplet, ,
, Applet. JApplet , Swing. JApplet , Applet.
, , () HTML- <applet>.
<applet> <param> name value.
: name
, , value , . getParameter().
12.12 HTML-, 12.13 Java- .
12.12. HTML-
<html>
<head><title> </title></head>
<body>
HTML-:<br>

372

12.

12.12 ()
<applet code="ShowText.class" width="600" height="90">
<param name="" value="">
<param name=" " value="">
<param name="" value="Arial">
<param name="" value="">
<param name="" value="28">
</applet>
</body>
</html>
12.13.
// :
import java.awt.*;
import java.applet.*;
// :
public class ShowText extends Applet{
// :
String text;
// :
private Color getColor(String color){
Color clr;
if(color.equals("")) clr=Color.YELLOW;
else if(color.equals("")) clr=Color.BLUE;
else if(color.equals("")) clr=Color.RED;
else clr=Color.WHITE;
return clr;
}
// :
public void init(){
// :
String color=getParameter("");
// :
setBackground(getColor(color));
// :
color=getParameter(" ");
// :
setForeground(getColor(color));
// :
String font=getParameter("");
// ( ):
String style=getParameter("");
// :
int stl;
// :
if(style.equals("")) stl=Font.BOLD;
else if(style.equals("")) stl=Font.ITALIC;

373

else stl=Font.PLAIN;
// :
int size=Integer.parseInt(getParameter(""));
// :
text=" "+font+" "+style+" "+size;
// :
setFont(new Font(font,stl,size));}
// :
public void paint(Graphics g){
g.drawString(text,30,getHeight()-30);}
}

HTML- 12.12 :
<paramname="1"value="2">

1 ,
, 2 . , <param
name=" " value=""> , ,
, .
getParameter()
. . , ,
getParameter() getParameter("
"),
"".
(.12.13), ShowText (getColor(), init() paint())
text. text , . init(),
paint() ( ),
.
text, init()
. String color=getParameter("")
color , HTML-. setBackground(getColor(color)) .
getColor(), color Color (
getColor() ). getColor() setForeground(getColor(color)), .
color=getParameter(" ")
color ,

374

12.

HTML-. String font=getParameter("").


String style=getParameter(""). , style .
( Font.BOLD, Font.ITALIC Font.PLAIN
). stl. ,
, style. , , , PLAIN.

getParameter(""). Integer.parseInt(),
, size.
intsize=Integer.parseInt(getParameter(""))

text=" "+font+" "+style+" "+size, setFont(new Font(font,stl,size))


.
getColor()
. Color.
clr Color. color. clr
( ). clr
.
,

paint()
g.drawString(text,30,getHeight()-30) ( g
) init() , , HTML-. .12.16 , HTML .
, .
HTML- , HTML,
. ,
.

375

. 12.16. HTML-

1. , : AWT Swing.
AWT.
2. .
, Frame ( AWT)
JFrame ( Swing).
, , , .
3. . Java
: , , .
.
4. ,
, Java- ,
.
Applet JApplet.
: , main(). .
,
.


,
Java. , ,
. , ,
.
. -,
Java. -,
,
. ,
, . , ,
Java. , .
, , ,
. ,
.


1. ., . Java 2: . .: , 2006.
1072 .
2. . Java. .: , 2008. 720 .
3. .., . Java 2. . .1, .
.:, 2009. 816 .
4. .., . Java 2. . .2,
. .:, 2010. 992 .
5. . Java NetBeans. .: , 2009.
720.
6. . Java: . .: , 2008. 720 .
7. . Java: . .: , 2008.
512.
8. .. Java. . .: , 2008. 224 .
9. . SWING Java: . .:
, 2007. 704 .
10. . Java SE 6. .: , 2010. 1040 .
11. . Java. .: ., 2009. 640 .


,
( ) Java.
, ,
. , Java, .



www.java.com,
Java. Internet Explorer ..1.
, .
JDK JRE.
, , . . NetBeans.
. NetBeans www.netbeans.org (..2).
,
Java . ,
.
Eclipse.
www.eclipse.org (..3).
NetBeans, Excipse
, Java.

. NetBeans, ,
.

. .1. - www.java.com

. .2. - www.netbeans.org

381

382

. .3. - www.eclipse.org

NetBeans
NeBeans 6.8 . .4.

. .4. NetBeans6.8

NetBeans

383

File NewProject,
..5.

. .5. FileNewProject

( ) -
(..6).

. .6.

NewProject, . .7.
Categories
( Java), Projects ( Java Application). Next
New Java Application (..8).
ProjectName . Project Location ( Browse ). , ..8
Create Main Class Set as Main Project (

384

) . NetBeans
..9.

. .7. NewProject

. .8. NewJavaApplication

NetBeans

385

. .9.

,
NewJava Class New File ( ).
New Java Class Class Name
(..10).

( , , ). , , ,
..12.
RunBuild Project
(..13).
. RunRun Project , (..14).
Run Prject,
(..15).
.
NetBeans
. .16. ( ) Output,
.
, Close Project File
Close (..17).

386

. .10.

. .11. NetBeans

NetBeans

. 14.12.

. .13.

. .14.

387

388

. .15.

. .16.
Output NetBeans

. .17.

NetBeans

389

, , , Open Project File (..18).

. .18.

(..19).

. .19.

OpenProject, , Open Project


(..20).

. .20.

390

NetBeans
, . , .

Eclipse
Eclipse NetBeans,
Java Eclipse. ..21 Eclipse, FileNewJava Project.

. .21.


, (..22).
New Java
Project (..23).

Eclipse

391

. .22.

. .23.

392

Project name . JRE


( ), . ..24 Eclipse ,
.

. .24.

FileNewClass
(..25) .
New Java Class (..26).
, Name . public Modifiers . ,
. public
static void main(String[]args) , .
..27.
..28.
(..29) Run.
, ..30.
, , , .
..31.

Eclipse

. .25.

. .26.

393

394

, ( )
Console Eclipse.
,
, . . .

. .27. Eclipse

. .28. Eclipse

Eclipse

. .29.

. .30.

. .31.

395

17, 363
19

111, 113, 198


212
233

20

29
25

122
111, 112
53
56, 59
233, 239, 325
262

17, 34, 111, 114, 319, 332, 339


218
126
18
301
220
153, 156
202
156
163

80
81
81
81
89
61

111, 124, 159


276
164
31

230
231
153
208
198
111, 113, 153
282, 299
293
23
32

118
198
24

31

231
49

17

Java. - :



.
.
.
.
.
.
.

27.08.10. 70100/16. . . . 32,25. 2000. 0000.


, 194044, -, . ., 29.
005-93, 2; 95 3005 .
CtP . . . .
197110, -, ., 15.

397


, ,
,

/ . , . ., . 29
./: (812) 7037373, 7037372; email: sales@piter.com
. , ., . 2/1, . 1, 6
./: (495) 23438-15, 97434-50; e-mail: sales@msk.piter.com

., . 169; ./: (4732) 396170


email: piterctr@omch.ru
. , . 11; ./: (343) 3789841, 3789842
mail: office@ekat.piter.com

. , . 13; .: (8312) 412731


email: office@nnov.piter.com
. , . 36; .: (383) 363-01-14
: (383) 3501979; email: sib@nsk.piter.com
//

. , . 26; .: (863) 2699122, 2699130


mail: piterug@rostov.piter.com

. , . 33; 223; .: (846) 2778979


e-mail: pitvolga@samtel.ru

. , . 12, 10; .: (1038057) 751-10-02


758-41-45; : (1038057) 712-27-05; -mail: piter@kharkov.piter.com

., . 6, . 1, 33; .: (1038044) 4903569


: (1038044) 4903568; mail: office@kiev.piter.com

. , . 34, 2; ./: (1037517) 201-48-79, 201-48-81


mail: gv@minsk.piter.com

, .
: (812) 703/73/73. E/mail: fuganov@piter.com
.
: / (812) 703/73/72, (495) 974/34/50
.: (812) 7037373.
mail: kozin@piter.com
: www.piter.com; .: (812) 703-73-74
ICQ 413763617

!



.


./: (4232) 238212
email: bookbase@mail.primorye.ru

,
.: (3952) 200917, 241777
email: prodalit@irk.ru
http://www.prodalit.irk.ru

, , . , . 1
.: (4212) 360665, 339531
email: dkniga@mail.kht.ru

,
./: (3952) 252590
email: kkcbooks@bk.ru
http://www.kkcbooks.ru

,
.: (4212) 328551, : (4212) 328250
email: postmaster@worldbooks.kht.ru
,
.: (4212) 394960
email: zakaz@booksmirs.ru

, , . , . 3
.: (8182) 654134, 653879
email: marketing@avfkniga.ru

, , . , . 4
.: (4732) 267777
http://www.amital.ru
, ,

./: (4012) 215628, 6 56568
email: nshibkova@vester.ru
http://www.vester.ru
, ,
, .15
.: (846) 3312233
email: chaconne@chaccone.ru
,
. , . 58
.: (4732) 512893, 470081
email: manager@kmsvrn.ru

, , . , 424
./: (87934) 69309
email: rossy@kmw.ru

,
. , . 86
./: (3912) 273971
email: bookworld@public.krasnet.ru
, 
.: (383) 3361026
: (383) 3361027
email: office@topkniga.ru
http://www.topkniga.ru

, ,

.: (843) 2723455
email: tais@bancorp.ru

,
. , . 12
./: (343) 3581898, 3581484
email: domknigi@k66.ru

,
. , . 1
./: (343) 228-10-70
e-mail: igm@lumna.ru
http://www.lumna.ru
,
. , . 124
.: (351) 2477403, 2477409,
2477416
email: zakup@intser.ru
http://www.fkniga.ru, www.intser.ru