Simple JAVA (Russian)
Simple JAVA (Russian)
ii
Java
Programming
for
Kids,
Parents
and
Grandparents
by
Yakov
Fain
Copyright
2011
Yakov
Fain
All
rights
reserved.
No
part
of
this
book
may
be
reproduced,
in
any
form
or
by
any,
without
permission
in
writing
from
the
publisher.
Cover
design
and
illustrations:
Yuri
Fain
Adult
technical
editor:
Yuri
Goncharov
Kid
technical
editor:
David
Fain
May
2004:
First
Electronic
Edition
(English)
June
2005:
Second
Electronic
Edition
(French)
Programmation
Java
pour
les
enfants,
les
parentset
les
grands-parents
October
2011:
Third
Electronic
Edition
(Russian)
Java
,
,
The
information
in
this
book
is
distributed
without
warranty.
Neither
the
author
nor
the
publisher
shall
have
any
liability
to
any
person
or
entitle
to
any
liability,
loss
or
damage
to
be
caused
directly
or
indirectly
by
instructions
contained
in
this
book
or
by
the
computer
software
or
hardware
products
described
herein.
Java
and
all
Java-based
trademarks
and
logos
are
trademarks
or
registered
trademarks
of
Oracle
Corporation
in
the
United
States
and
other
countries.
Windows
7
and
Windows
XP
are
trademarks
of
Microsoft
Corporation.
All
other
product
names
and
company
names
are
the
property
of
their
respective
owners.
ISBN:
0-9718439-5-3
Java , ,
iii
,
,
.
,
(
)
.
2004
-,
,
.
.
,
.
,
http://yurifain.com.
. ?
,
-
.
,
.
mp3
,
.
http://americhka.us
.
,
,
,
-
3-4
,
,
Java
,
.
,
,
,
,
.
:
,
,
,
,
,
!
,
,
,
,
.
,
.
,
.
,
,
,
,
J.
,
.
,
.
.
Java , ,
iv
,
.
,
?
,
,
.
,
,
Java
,
,
.
,
,
,
.
-
,
,
-
,
.
,
([email protected]),
.
,
,
,
,
,
Java!
Java , ,
,
-
,
Java
.
,
.
Java
,
!
Amazon
(
-)
,
,
!
,
Google,
,
Java
,
,
Reader-Rabbit.
,
?
.
,
-
.
,
:
11
18
;
;
,
;
(
).
,
,
.
,
-
!
.
, !
.
-,
,
.
,
a.
-
-.
.
.
Java , ,
Java
,
,
String.
Java.
,
.
a
,
-
.
,
.
,
.
,
.
,
,
.
,
.
,
.
,
,
,
,
.
vi
Java , ,
,
Eclipse,
.
New
Jersey
Transit
139.
.
,
Java
,
.
,
,
.
vii
Java , ,
viii
......................................... III
...................................................................................... V
............................................................................... VII
..................................................................................... VIII
1. ....................................................... 13
Java ............................................................................................................. 14
........................................................................... 18
1 ............................................................................................. 18
2 ........................................................................................... 20
3 ..................................................................................................... 21
............................................................................ 22
3. JAVA .... 40
..................................................................................................................... 40
............................................................................................................................. 42
................................................................................................. 46
............................................................ 52
........................................................................................................ 56
........................................................................................................... 57
Java , ,
ix
..................................................................................................... 57
............................................................. 58
4. JAVA .................... 59
...................................................................................................... 59
if ....................................................................... 60
............................................................................................................. 62
. ............................................................................................................ 63
................................................................................................................... 63
else if............................................................................................................... 64
switch .............................................................................. 65
? ............................................................................................... 66
: ................................................................................... 67
this ............................................................................................................... 68
...................................................................................................................................... 69
............................................................................ 71
............................................................................ 74
...................................................................................................... 74
............................................................. 75
5. ....................... 76
AWT Swing ............................................................................................................................... 76
import ........................................................................................... 77
Swing ...................................................................................................... 78
................................................................................................................... 81
FlowLayout - ................................................................................ 82
GridLayout - ................................................................................. 82
BorderLayout - .............................................................................. 84
....................................................................................... 85
BoxLayout - .............................................. 88
GridBag Layout - .................................................. 89
Java , ,
CardLayout ........................................................................................................ 90
, ? ................................................................. 91
...................................................................................................................... 91
............................................................................ 95
...................................................................................................... 95
............................................................. 96
6. ............................................................... 97
................................................................................................................................ 98
ActionListener .................................................................................... 100
ActionListener ........................................................................ 101
- -? ......................................................................................................... 102
- casting .................................................................................................... 102
........................................................................... 105
...................................................................................................... 106
.............................................................................. 112
.................................................................................................. 114
.......................................................................... 115
.................................................................................................... 115
........................................................... 115
7. - ........................................ 116
HTML
15
................................................................................................. 117
A
AWT ...................................................................................................................... 120
................................................................................................................ 121
- ............................................................................................. 123
.................................................................................................................................. 124
.................................................................................................................... 124
.......................................................................... 134
.................................................................................................... 135
........................................................... 136
8. .............. 137
Java , ,
xi
..................................................................................................... 138
.................................................................................. 139
try/catch ........................................................................................................................... 141
throws ........................................................................................................... 144
finally ............................................................................................................ 145
throw ............................................................................................................ 147
................................................................................................. 148
.......................................................................... 150
.................................................................................................... 151
........................................................... 151
9. .......................................... 152
..................................................................................................................... 153
................................................................................................ 155
.............................................................................................. 157
..................................................................................................... 160
File .................................................................................................................................. 164
.......................................................................... 166
.................................................................................................... 166
........................................................... 167
Java , ,
xii
........................................................... 191
. - .......... 225
.......................................................................... 229
.................................................................................................... 229
............................................................................................... 230
Java , ,
13
1.
.
,
,
,
,
.
,
.
,
.
C#
Java.
Java
?
-,
Java
()
-
,
PC,
Apple
.
,
Java
,
,
,
JVM
(Java
Virtual
Machine).
,
,
Java
-
,
JVM,
,
.
,
Java
(),
.
,
Java
Car
()
,
,
,
,
.
,
,
,
,
Ford,
Java , ,
14
Car
,
Ford.
,
Java
( ),
, Java
ee
.
,
Java
!
e
Java,
!
Java
Java,
()
-
Oracle.
Java
Sun
Microsystems.
2009
Oracle
Sun
Microsystems.
Java
Development
Kit
(JDK).
(JDK
7)
-:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Java
SE
7
.
Download
JDK
.
.
,
,
.
Windows,
Windows
x86
(32-
)
Windows
x64
(64-
).
Linux
Solaris,
.
Apple
JDK.
Apple,
,
Java
Enter.
Command
not
found,
Java
,
:
Java , ,
15
http://support.apple.com/downloads/#Java
.
.
Windows
:
Java , ,
16
.
,
Windows
:
C:\Program Files\Java\jdk1.7.0,
:
.
:,
.
Next,
Install
Finish
.
Java
.
.
,
Windows
,
.
Java , ,
17
.
...
Windows
7.
,
,
:
Path,
Windows
(
Unix)
JDK
.
,
Java.
Path
,
Java
:
Java , ,
18
CLASSPATH.
,
a
(.;).
Java
.
,
Java
.
,
.
,
JDK
!
Java
.
Java
.
,
Java
-,
JVM.
.
Java , ,
19
Java,
,
,
.
,
,
.java.
,
HelloWorld,
(
)
HelloWorld.java. ,
Java-.
,
Hello
World:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
,
Hello
World
.
Java , ,
20
2
.
javac,
JDK.
,
C:\practice.
,
cmd
.
.
,
PATH
CLASSPATH,
set.
.
C:\practice
:
cd \practice
javac HelloWorld.java
practice
,
.
javac
Java.
-
,
HelloWorld
.
,
!
dir.
,
.
,
HelloWorld.class.
,
Java , ,
21
.
HelloWorld.java
.
,
,
-
.
,
,
,
Java
.
.
,
,
HelloWorld.class.
,
.
:
java HelloWorld
,
java,
javac?
JRE
(Java
Run-time
Environment)
JVM,
HelloWorld.
,
Java
,
,
HelloWorld
H
W,
helloworld
helloWorld
JVM
, , , .
,
.
,
.
,
,
!
,
.
Java , ,
22
,
,
J.
,
,
,
.
:
http://download.oracle.com/javase/tutorial/getStarted/c
upojava/win32.html
Java
Windows:
http://download.oracle.com/javase/7/docs/webnotes/in
stall/windows/jdk-installation-windows.html
Java , ,
23
2. Eclipse IDE
IDE
(Integrated
Development
Environment).
,
.
IDE
,
,
,
.
IDE
,
IDE
Eclipse.
-
www.eclipse.org.
Eclipse
IDE
Hello World.
.
Eclipse
,
Java.
Eclipse IDE
-
www.eclipse.org
Download
Eclipse
(
Eclipse).
Java , ,
24
Eclipse
Downloads,
.
Eclipse
IDE
for
Java
Developers.
,
,
.
Windows
,
32-
.
Java , ,
25
,
,
.
,
,
.
,
(
).
Java , ,
26
C:.
.
,
ZIP
.
.
.
Java , ,
27
Eclipse
!
Eclipse.
.
>
>
C:\eclipse
eclipse.exe.
,
Eclipse.
Eclipse
(workspace)
,
.
Workspace
(
)
,
C:\workspace.
,
Eclipse
Java , ,
28
,
Use
this
as
the
default
and
do
not
ask
again
(
).
OK.
Eclipse
Welcome.
Eclipse.
Workbench
(
),
Java.
,
Welcome.
Eclipse
,
Java
Eclipse.
Eclipse.
Help
(),
Help
Contents
(
),
Java , ,
29
Location
().
,
.
Java , ,
30
.
,
Eclipse.
,
-
.
.
Eclipse
,
(perspective).
,
Window
(),
Open
Perspective
(
)
.
,
.
,
Java
Java,
Debug
().
My
First
Project,
JRE System
Library (jdk 1.7.0).
.
-
,
.
Windows
(),
Preferences
().
Java,
Editor
(),
Installed
JREs
(
JRE).
Add
().
Java , ,
31
Standard
VM
(
).
Next
().
Directory
,
Java,
,
C:\Program Files\Java\jdk1.7.0\.
Java , ,
32
Finish.
JRE.
Eclipse IDE
HelloWorld
1
Eclipse.
Java
,
.
.
Eclipse,
File,
New,
Class.
HelloWorld
Name
().
Which
methods
stubs
you
would
like
to
create
(
?)
main():
public static void main(String[] args)
Java , ,
33
Finish
Eclipse
HelloWorld,
main().
.
,
Java
,
,
main().
public class HelloWorld {
public static void main(String[] args) {
}
,
main,
Enter
:
Java , ,
34
System.out.println("Hello World");
,
Ctrl-S.
,
,
.
,
,
.
Ctrl-S.
Problems
Eclipse
Syntax
error,
insert
"}"
to
complete
ClassBody
(
;
"}"
ClassBody).
,
,
.
,
.
,
,
.
.
Problems.
Ctrl-S
,
!
Java , ,
35
HelloWorld Eclipse
,
.
,
Eclipse
,
.
Run
(),
Run
Configurations
().
,
Java
Application
(
Java).
Main
Project
()
,
Main
class
(
)
.
,
,
Run
().
Console
()
Hello
World,
,
1.
o
Run
(),
Run
()
Ctrl-F11.
Java , ,
36
HelloWorld
-
HelloWorld?
HelloWorld
main(),
Java.
,
main
,
main.
()
,
,
main(),
Hello World,
println().
,
:
public static void main(String[] args)
public.
public
,
main()
Java
JVM.
static.
static
,
()
HelloWorld
,
.
.
-
?
void
,
main()
,
.
Eclipse.
,
-
,
.
-
main.
,
String[] args.
main()
Java , ,
37
String[] args ,
String,
.
,
,
.
,
,
main().
Java
.
,
Game
startGame(), stopGame(), readScore()
.
main()
:
System.out.println("Hello World");
(;).
println()
(
).
Java
.
,
,
.
System.out
,
out
System,
Java.
,
System
-
out?
Eclipse
.
,
System
,
Eclipse
,
.
Ctrl-Space,
,
.
Java , ,
38
out.println()
,
,
out
-
out
println().
,
,
.
,
PingPongGame,
saveScore()
.
,
,
:
PingPongGame.saveScore("", 3);
,
.
,
,
,
.
saveScore()
,
3.
Eclipse
,
,
?
,
Java
IDE.
Eclipse IDE Tutorial by Lars Vogel:
http://www.vogella.de/articles/Eclipse/article.html
Java , ,
39
HelloWorld,
println().
HelloWorld,
Hello
,
.
Java , ,
40
3.
Java
Java ,
.
-,
,
,
-
.
,
,
Java
,
.
,
VideoGame
(
).
,
,
:
,
,
()
.
-
,
,
,
,
.
Java
.
,
.
.
Java , ,
41
:
class VideoGame {
int color; //
String int price; //
void start () {
}
void stop () {
}
void saveScore(String playerName, int score) {
}
}
K
VideoGame
,
,
,
,
,
.
GameBoyAdvance
-
.
,
,
GameBoy
Advance,
.
GameBoyAdvance
cartridgeType
and
screenWidth
startGame()
stopGame().
-
,
.
class GameBoyAdvance {
Java , ,
42
String cartridgeType; //
int screenWidth; //
void startGame() {
}
void stopGame() {
}
}
GameBoy
Advance
,
Java-
.
,
GameBoyAdvance
Java.
.
.
,
,
-
-
,
-
,
.
,
GameBoyAdvance.
Java , ,
43
.
-
.
,
-
.
,
.
y=x+2?
Java
x
y,
-
,
(integer
int)
(double):
int x;
int y;
.
,
:
x=5;
y=x+2;
Java
.
,
:
int y=5;
y++;
,
Java
.
,
myScore
:
int myScore=5;
myScore=myScore+1;
,
,
:
int myScore=10;
Java , ,
44
myScore--;
myScore=myScore*2;
myScore=myScore/3;
System.out.println("My score is " + myScore);
-
(,
My
score
is
)?
Eclipse,
,
(scrapbook)
.
File,
New,
Scrapbook
Page
Test
-.
,
:
,
Console
:
My
score
is
6
println()
My
score
is
myScore,
.
(concatenation).
,
myScore
,
:
Java
,
String
My
Score
is.
Java , ,
45
,
:
myScore=myScore*2;
// myScore*=2;
myScore=myScore+2;
// myScore+=2;
myScore=myScore-2;
// myScore-=2;
myScore=myScore/2;
// myScore/=2;
Java
()
,
s
.
,
,
,
:
byte,
short,
int,
and
long.
float
double.
char.
,
boolean,
:
true
false
(
).
Java
.
:
char grade = 'A';
intirs = 12;
cha boolean playSound = false;
double nationalIncome = 23863494965745.78;
float gamePrice = 12.50f;
long totalCars =4637283648392l;
f
float,
l
long.
-
,
Java
,
false
boolean,
\u0000
char.
final,
,
.
final-
Java , ,
46
.
.
final String STATE_CAPITAL=;
,
.
-,
Integer,
Double,
Boolean,
.
,
.
char
,
Java
String
:
String lastName=;
.
,
.
1
0.
.
char
.
int
float
.
long
double
.
,
,
.
1
(KB)
-
1024
1
(MB)
-
1024
1
(GB)
1024
(-
Pet).
,
Pet
.
,
(eat,
sleep,
say)
?
Java , ,
47
Pet.
:
(age),
(height),
(weight)
(color).
Pet
My
First
Project
,
,
main().
:
Pet.
.
:
class Pet{
}
.
int
,
float
,
String
.
class Pet{
Java , ,
48
int age;
float weight;
float height;
String color;
}
.
-
:
sleep()
,
.
eat()
!
say()
,
,
,
.
,
,
.
Pet
:
public class Pet {
int age;
float weight;
float height;
String color;
public void sleep(){
System.out.println(" ! ");
}
public void eat(){ System.out.println(
" , !");
}
public String say(String aWord){
String petResponse = " !! " +aWord;
return petResponse;
}
}
Java , ,
49
()
sleep():
public void sleep()
,
sleep()
(public)
(void).
,
,
.
say()
:
public String say(String aWord)
,
-
String,
.
,
-
String aWord.
Java , ,
50
?
-
,
.
,
Pet
!
,
PetMaster
().
main(),
Pet.
PetMaster,
Eclipse
-
main().
,
.
,
Eclipse,
:
public class PetMaster {
public static void main(String[] args) {
String petReaction;
Pet myPet = new Pet();
myPet.eat();
petReaction = myPet.say("!! !!");
System.out.println(petReaction);
myPet.sleep();
}
}
Ctrl-S
,
!
PetMaster,
Eclipse
Run,
Run,
New
-
Java , ,
51
PetMaster.
Run
,
:
, !
!! !! !!
,
PetMaster
Pet.
myPet
and
new:
Pet myPet = new Pet();
myPet
Pet
(
,
,
,
).
myPet
,
Pet,
,
Pet,
:
myPet.eat();
-
,
-.
-
,
,
,
:
String petReaction;
petReaction = myPet.say("!! !!");
petReaction
:
System.out.println(petReaction);
Java , ,
52
Pet
Java,
(inheritance).
-
.
Java
.
Pet,
,
,
,
,
.
,
,
,
,
.
-,
,
,
.
Fish
()
,
Pet,
,
.
extends:
Fish
-
Pet,
Pet
-
Fish.
Pet,
Fish.
class Fish extends Pet{
Java , ,
53
Fish
,
,
,
Pet.
:
Fish myLittleFish = new Fish();
myLittleFish.sleep();
Fish,
sleep(),
-!
Eclipse!
File,
New,
Class
Fish,
.
-
java.lang.Object
Pet.
Java , ,
54
,
Pet,
,
,
,
-,
.
,
,
,
.
Fish
dive()
-
.
dive()
howDeep,
,
.
currentDepth,
dive().
currentDepth
.
,
,
FishMaster:
Java
-
Object,
extends.
,
Java-
.
Java
,
,
,
-
.
public class Fish extends Pet {
int currentDepth=0;
public int dive(int howDeep){
currentDepth=currentDepth + howDeep;
System.out.println(" "
+ howDeep + " ");
System.out.println(" "
+ currentDepth + " ");
return currentDepth;
}
}
Java , ,
55
myFish.sleep();
}
}
FishMaster
:
2
2
3
5
,
,
FishMaster
Fish,
sleep()
-
Pet?
-!
Pet.
extends
Fish
Pet!
Java , ,
56
,
,
dive()
currentDepth,
FishMaster
.
,
FishMaster
.
-
,
Fish,
.
,
,
FishTrafficDispatcher
(
),
,
-
.
,
,
,
(
).
Fish
Pet,
say().
,
-
:
myFish.say();
,
,
Fish
(override)
say(),
Pet.
:
-
-
,
-
-,
Java
-,
-.
Fish
say().
public String say(String something){
return " , ?";
}
say()
main()
FishMaster:
myFish.say("");
:
, ?
,
say()
Pet
.
!
.
final,
,
:
Java , ,
57
1.Java
Data
Types:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/da
tatypes.html
2.About
inheritance:
http://java.sun.com/docs/books/tutorial/java/concepts/inherit
ance.html
1.
Car
()
:
public void start()
public void stop()
public int drive(int howlong)
drive()
()
.
:
distance = howlong*60;
2.
CarOwner
(
),
Car
.
System.out.println().
Java , ,
58
Car,
JamesBondCar
(
)
drive().
:
distance = howlong*180;
!
.
Java , ,
59
4.
Java
, Java,
,
,
,
.
,
,
.
-
.
:
1.
,
:
//
2.
/*
*/,
:
/* 3
.
*/
3.
Java
javadoc,
.
.
Java , ,
60
/**
*/.
,
,
.
/**
. $100,
= 20%, 10%.
*/
,
,
.
if
:
,
-
.
Java
if,
,
(true)
(false).
,
,
.
,
?
true,
,
.
,
JVM
,
,
else.
,
100
,
20%
,
10%.
// 20%
if (price > 100){
Java , ,
61
price=price*0.8;
System.out.println(" 20%);
}
else{
price=price*0.9;
System.out.println(" 10%);
}
dive()
Fish,
,
:
public class Fish extends Pet {
int currentDepth=0;
public int dive(int howDeep){
currentDepth=currentDepth + howDeep;
if (currentDepth > 100){
System.out.println(" "+
" 100 ");
currentDepth=currentDepth - howDeep;
}else{
System.out.println(" " + howDeep +
" ");
return currentDepth;
FishMaster
100
:
public class FishMaster {
Java , ,
62
,
:
2
2
97
99
100
,
,
,
.
,
(Texas)
(California),
.
.
(true),
-
(true).
Java
.
String.
a
Java
equals()
,
state
()
:
if (state.equals("Texas") | state.equals("California"))
if:
if (state.equals("Texas") || state.equals("California"))
Java , ,
63
,
,
(true),
.
, JVM
.
(&&).
,
.
,
,
(state)
-
(price)
110
.
:
if (state.equals("New York") && price >110)
if (state.equals("New York") & price >110)
(false),
,
..
,
.
.
(negation)
.
.
,
,
-
,
:
if (!state.equals("New York"))
:
if (price < 50)
if (!(price >=50))
if,
.
,
,
,
.
,
Java , ,
64
,
-
:
discount = price > 50? 10:5;
,
discount
()
,
-
.
if:
if (price > 50){
discount = 10;
} else {
discount = 5;
}
else if
if
else if .
ReportCard
(
),
main(),
,
.
,
(A,
B,
C,
D).
convertGrades().
public class ReportCard {
/**
M convertGrades
- A, B, C or D
.
*/
public char convertGrades( int testResult){
char grade;
if (testResult >= 90){
grade = 'A';
}else if (testResult >= 80 && testResult < 90){
grade = 'B';
}else if (testResult >= 70 && testResult < 80){
grade = 'C';
}else {
grade = 'D';
}
return grade;
Java , ,
65
}
public static void main(String[] args){
ReportCard rc = new ReportCard();
char yourGrade = rc.convertGrades(88);
else if
,
char.
,
&&
,
.
" testResult
80
89",
Java
,
testResult
80, (&)
89,
:
testResult >= 80 && testResult < 89
,
||.
switch
switch
if.
switch ,
case ,
:
public static void main(String[] args){
ReportCard rc = new ReportCard();
char yourGrade = rc.convertGrades(88);
switch (yourGrade){
case 'A':
System.out.println(" !");
break;
case 'B':
System.out.println(" !");
break;
case 'C':
System.out.println(" !");
break;
Java , ,
66
case 'D':
System.out.println(" !");
break;
}
break
case
,
,
switch.
break,
,
,
yourGrade
.
switch
,
,
:
char
int
byte
short
enum
Java
1.7,
String
switch.
,
,
Java
1.5
:
Character,
Byte,
Short,
Integer.
convertGrades()
ReportCard
grade.
,
.
,
.
,
,
.
Java , ,
67
(scope)
,
.
,
.
Fish,
currentDepth
(member
variable).
Fish,
(instance
variables).
,
,
,
.
,
System.out.println()
out,
System.
!
System,
?
,
static ().
static,
,
.
.
,
convertGrades()
ReportCard
,
,
.
sqrt()
Math
:
double squareRoot = Math.sqrt(4.0);
:
Java
new,
:
Fish myFish = new Fish();
Fish
,
Fish().
,
,
(constructors)
,
:
Java , ,
68
.
,
.
,
void
.
.
,
Java
(default
no-
argument
constructor).
new
Fish(),
Fish
.
,
,
,
Fish
,
currentDepth
.
public class Fish extends Pet {
int currentDepth;
Fish(int startingPosition){
currentDepth=startingPosition;
}
FishMaster
Fish
.
Fish,
20
:
Fish myFish = new Fish(20);
,
,
.
-
.
this
this
,
.
:
Java , ,
69
class Fish {
int currentDepth ;
Fish(int currentDepth){
this.currentDepth = currentDepth;
}
this
,
this.currentDepth
currentDepth,
currentDepth
.
,
Fish
this.
this,
6
.
,
o.
,
String,
,
String.
,
:
String [] players;
String players[];
Java,
players.
,
.
Java , ,
70
,
String,
:
String players[] = new String [4];
players[0]
players[1]
players[2]
players[3]
=
=
=
=
"David";
"Daniel";
"Anna";
"Gregory";
,
,
.
,
.
,
Java,
,
ArrayList,
.
length,
,
,
:
int
totalPlayers = players.length;
,
,
,
Java
:
String [] players = {"David", "Daniel", "Anna", "Gregory"};
,
.
,
:
String theWinner = players[1];
Java , ,
71
:
, Daniel!
,
[1]?
,
,
[0].
(one-dimensional),
.
,
.
Java
(multi-dimensional
arrays).
,
,
10.
,
-
.
,
.
-
for:
int totalPlayers = players.length;
int counter;
for (counter=0; counter <totalPlayers; counter++){
String thePlayer = players[counter];
System.out.println(", "+ thePlayer+"!");
}
JVM
,
,
counter
()
.
:
,
.
0
(counter=0),
counter
(counter++).
,
counter
totalPlayers
(counter<totalPlayers).
-
while.
,
Java , ,
72
,
.
,
while,
,
counter
()
totalPlayers:
int totalPlayers = players.length;
int counter=0;
while (counter< totalPlayers){
String thePlayer = players[counter];
System.out.println(", "+ thePlayer + "!");
counter++;
}
9
,
.
,
,
,
.
,
while.
:
break
continue.
break
,
,
(true).
,
,
,
.
,
0,
1
2,
-
break
.
if.
counter
3.
,
3
counter.
==
=
if,
,
:
int counter =0;
while (counter< totalPlayers){
if (counter == 3){
break; //
}
Java , ,
73
continue
,
.
,
,
continue
.
while (counter< totalPlayers){
counter++;
String thePlayer = players[counter];
if (thePlayer.equals("David"){
continue;
}
}
while,
do,
:
do {
// , -
} while (counter< totalPlayers);
,
.
,
.
,
while
,
,
(false).
Java , ,
74
Java:
http://download.oracle.com/javase/tutorial/java/index.h
tml
1.
TemperatureConverter.
,
:
convertTo
F,
,
C,
.
,
char
.
2.
convertGrades()
ReportCard
main().
Java , ,
75
,
continue
counter++;
?
,
,
break?
Java , ,
76
5.
ava ,
.
Java.
AWT Swing
Java
-
AWT.
,
,
Button
(),
TextField
(
),
Label
(
)
.
,
Swing.
,
.
J.
,
JButton,
JTextField
.
Swing
,
,
JVM,
Swing.
Java , ,
77
import
Java
,
(packages).
,
.
,
String
java.lang
java.lang.String.
Java
,
,
java.lang,
String
,
,
,
.
,
Swing
:
javax.swing
javax.swing.event
,
,
.
,
import
,
:
import javax.swing.JFrame;
import javax.swing.JButton;
class Calculator{
JButton myButton = new JButton();
JFrame myFrame = new JFrame();
}
import
,
JFrame
JButton
,
.
,
import,
*.
,
javax.swing
:
import javax.swing.*;
Java , ,
78
,
import
.
,
.
10.
Swing
,
Swing-
:
(frame),
JFrame.
(panel)
,
,
pane
(
)
,
,
.
JPanel.
,
JButton,
JTextfield,
JList,
.
(layout
managers)
,
.
,
JPanel
.
.
Java , ,
79
.
,
.
,
,
(events),
.
,
.
Eclipse,
My
Calculator
SimpleCalculator
:
Java , ,
80
import javax.swing.*;
import java.awt.FlowLayout;
public class SimpleCalculator {
public static void main(String[] args) {
//
JPanel windowContent= new JPanel();
//
FlowLayout fl = new FlowLayout();
windowContent.setLayout(fl);
//
JLabel label1 = new JLabel("Number 1:");
JTextField field1 = new JTextField(10);
JLabel label2 = new JLabel("Number 2:");
JTextField field2 = new JTextField(10);
JLabel label3 = new JLabel("Sum:");
JTextField result = new JTextField(10);
JButton go = new JButton("Add");
//
windowContent.add(label1);
windowContent.add(field1);
windowContent.add(label2);
windowContent.add(field2);
windowContent.add(label3);
windowContent.add(result);
windowContent.add(go);
//
JFrame frame = new JFrame("My First Calculator");
frame.setContentPane(windowContent);
//
frame.setSize(400,100);
frame.setVisible(true);
}
.
:
Java , ,
81
,
,
,
,
.
.
.
,
.
,
,
,
(users).
Java
(Layout
Managers),
,
.
,
,
,
.
Swing
:
FlowLayout
GridLayout
BoxLayout
BorderLayout
CardLayout
GridBagLayout
,
-
Java , ,
82
(container),
,
SimpleCalculator.
FlowLayout -
e
(
)
.
,
,
,
,
.
,
.
,
.
,
.
java.awt.FlowLayout
.
,
this
SimpleCalculator.
FlowLayout fl = new FlowLayout();
this.setLayoutManager(fl);
,
FlowLayout
.
-
.
GridLayout -
java.awt.GridLayout
,
.
.
,
,
.
,
.
(
):
GridLayout gr = new GridLayout(4,2);
Java , ,
83
,
:
GridLayout gr = new GridLayout(4,2,5,5);
(
),
.
SimpleCalculatorGrid
My
Calculator.
import javax.swing.*;
import java.awt.GridLayout;
public class SimpleCalculatorGrid {
public static void main(String[] args) {
//
JPanel windowContent= new JPanel();
//
GridLayout gl = new GridLayout(4,2);
windowContent.setLayout(gl);
//
JLabel label1 = new JLabel("Number 1:");
JTextField field1 = new JTextField(10);
JLabel label2 = new JLabel("Number 2:");
JTextField field2 = new JTextField(10);
JLabel label3 = new JLabel("Sum:");
JTextField result = new JTextField(10);
JButton go = new JButton("Add");
//
windowContent.add(label1);
windowContent.add(field1);
windowContent.add(label2);
windowContent.add(field2);
windowContent.add(label3);
windowContent.add(result);
windowContent.add(go);
Java , ,
84
//
JFrame frame = new JFrame("My First Calculator");
frame.setContentPane(windowContent);
//
frame.setSize(400,100);
frame.setVisible(true);
}
SimpleCalculatorGrid, :
,
:
,
.
BorderLayout -
java.awt.BorderLayout
,
,
,
.
,
,
,
.
,
,
Java , ,
85
,
,
,
.
BorderLayout
:
BorderLayout bl = new BorderLayout();
this.setLayoutManager(bl);
JTextField txtDisplay = new JTextField(20);
this.add("North",
txtDisplay);
.
,
,
,
..
.
BorderLayout
,
,
Calculator.java.
,
GridLayout
,
,
Microsoft
Windows?
,
,
.
,
.
Java , ,
86
.
:
BorderLayout
,
,
.
JTextField
,
.
p1
GridLayout,
20
.
p2
GridLayout,
p2
.
,
:
Calculator
.
,
,
,
.
import
import
import
public
javax.swing.*;
java.awt.GridLayout;
java.awt.BorderLayout;
class Calculator {
// .
JPanel windowContent;
JTextField displayField;
JButton button0;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
Java , ,
JButton button8;
JButton button9;
JButton buttonPoint;
JButton buttonEqual;
JPanel p1;
//
//
// Borderlayout Gridlayout
Calculator(){
windowContent= new JPanel();
//
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
//
//
displayField = new JTextField(30);
windowContent.add("North",displayField);
// ,
// JButton,
//
button0=new JButton("0");
button1=new JButton("1");
button2=new JButton("2");
button3=new JButton("3");
button4=new JButton("4");
button5=new JButton("5");
button6=new JButton("6");
button7=new JButton("7");
button8=new JButton("8");
button9=new JButton("9");
buttonPoint = new JButton(".");
buttonEqual=new JButton("=");
// GridLayout
// 12 - 10
//
p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);
//
p1
p1.add(button1);
p1.add(button2);
p1.add(button3);
p1.add(button4);
p1.add(button5);
p1.add(button6);
p1.add(button7);
87
Java , ,
88
p1.add(button8);
p1.add(button9);
p1.add(button0);
p1.add(buttonPoint);
p1.add(buttonEqual);
// p1
windowContent.add("Center",p1);
//
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
//
// ,
frame.pack();
// ,
frame.setVisible(true);
}
public static void main(String[] args) {
Calculator calc = new Calculator();
}
BoxLayout -
java.swing.BoxLayout
(
)
(
).
FlowLayout,
BoxLayout
,
.
BoxLayout
(
GridLayout).
box
layout
JPanel.
JPanel p1= new JPanel();
setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
,
BoxLayout,
,
setLayout().
Java , ,
89
GridBag Layout -
.
java.awt.GridBagLayout
.
,
GridLayout
.
,
,
.
GridBagLayout
-
.
,
.
GridBagLayout
,
GridBagConstraints
(
).
,
,
.
,
.
,
GridBagConstraints
gridWidth.
-
,
.
GridBagLayout
GridBagConstraints,
.
,
.
Java , ,
90
,
,
,
GridBagLayout.
// GridBagLayout
GridBagLayout gb = new GridBagLayout();
this.setLayout(gb);
// GridBagConstraints
//
//
GridBagConstraints constr = new GridBagConstraints();
//
// x
constr.x=0;
// y
constr.y=0;
// ,
constr.gridheight =1;
// 6
constr.gridwidth= 6;
//
constr.fill= constr.BOTH;
// ,
constr.weightx = 1.0;
// ,
constr.weighty = 1.0;
//
constr.anchor=constr.CENTER;
displayField = new JTextField();
//
gb.setConstraints(displayField,constr);
//
windowContent.add(displayField);
CardLayout
,
,
.
java.awt.CardLayout
a,
,
,
.
Java , ,
91
.
,
,
,
.
,
"
"
.
,
,
Swing
.
JTabbedPane.
,
?
,
!
a
.
,
.
Java
null,
.
,
,
:
windowContent.setLayout(null);
,
,
,
.
,
40
,
20,
100
200
:
JButton myButton = new Button("New Game");
myButton.setBounds(100,200,40,20);
Swing
,
Swing,
.
Swing.
JButton,
JLabel
JTextField.
:
Java , ,
92
JButton
JLabel
JCheckBox
JRadioButton
JToggleButton
JScrollPane
JSpinner
JTextField
JTextArea
JPasswordField
JFormattedTextField
JEditorPane
JScrollBar
JSlider
JProgressBar
JComboBox
JList
JTabbedPane
JTable
JToolTip
JTree
JViewPort
ImageIcon
(JMenu
JPopupMenu),
,
(JInternalFrame)
(JFileChooser,
JColorChooser
JOptionPane).
Java
,
Swing
.
,
Java
SDK,
C:\Program
Files\Java\jdk1.6.0_19\demo\jfc\SwingSet3.
:
https://swingset3.dev.java.net.
SwingSet3.html,
,
:
Java , ,
93
,
,
Swing
.
,
,
Source
Code.
,
combobox
(
),
,
:
Java , ,
94
Swing
,
.
Swing
,
,
.
,
.
Java
Swing.
,
Swing
,
Matisse.
Gigloo
GUI
Builder.
,
.
Java , ,
95
1.
Swing:
http://download.oracle.com/javase/tutorial/uis
wing/index.html
2.
JFormattedTextField:
http://download.oracle.com/javase/7/docs/api
/javax/swing/JFormattedTextField.html
1.
Calculator.java
+,
-,
/,
*.
p2,
.
2.
JFormattedTextField
,
JTextField.
,
.
Java , ,
96
Calculator.java
,
,
:
10
,
button0=new JButton("0"); ,
.
:
-
7.
Java , ,
97
6.
:
,
-
,
.
,
5,
.
,
,
,
.
Java,
(listeners),
.
,
,
.
,
,
,
,
.
MouseMotionListener
.
,
.
ActionListener,
.
Java,
.
Java , ,
98
,
,
,
,
,
.
.
,
,
,
,
:
interface MouseMotionListener {
void mouseDragged(MouseEvent e);
void mouseMoved(MouseEvent e);
}
,
mouseDragged()
mouseMoved()
,
MouseMotionListener.
,
.
implements
,
,
,
:
Java , ,
99
import java.awt.event.MouseMotionListener;
class MyDrawingPad implements MouseMotionListener{
// ,
//
mouseDragged(MouseEvent e){
// ,
// -
}
mouseMoved(MouseEvent e){
// ,
//
}
,
,
?
,
,
,
.
,
(
JVM)
,
MyDrawingPad
MouseMotionListener,
,
mouseDragged()
mouseMoved().
,
,
JVM
mouseMoved()
,
.
,
mouseMoved(),
movedMouse(),
mouseCrawling()?
JVM
,
,
.
Java
,
,
:
class myDrawingProgram implements MouseMotionListener,
ActionListener {
//
// o ax
}
,
,
Java,
,
,
,
.
Java , ,
100
ActionListener
.
,
.
-,
-
,
.
-,
,
,
Calculator.java,
.
CalculatorEngine,
,
java.awt.ActionListener
-
actionPerformed(ActionEvent).
JVM
,
,
-
.
:
import java.awt.event.ActionListener;
public class CalculatorEngine implements ActionListener {
}
(
Eclipse),
,
,
,
actionPerformed(ActionEvent e).
:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CalculatorEngine implements ActionListener {
public void actionPerformed(ActionEvent e){
// ,
// , JVM
}
}
(a
message
box)
actionPerformed().
JOptionPane
showConfirmDialog()
.
,
CalculatorEngine
:
Java , ,
101
showConfirmDialog(),
.
null
,
,
,
,
,
(PLAIN_MESSAGE
,
-
OK).
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
public class CalculatorEngine implements ActionListener {
public void actionPerformed(ActionEvent e){
JOptionPane.showConfirmDialog(null,
"Something happened...", "Just a test",
JOptionPane.PLAIN_MESSAGE);
}
,
,
Something
happened.
ActionListener
,
actionPerformed()?
JVM
,
CalculatorEngine
(
)!
Calculator
,
:
Java , ,
102
,
button0,
JVM
actionPerformed()
CalculatorEngine.
Calculator
Something
happened!
,
.
,
:
button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
-
-?
,
,
.
,
JVM
-
actionPerformed(ActionEvent),
ActionEvent.
,
-.
- casting
,
,
,
getSource()
ActionEvent.
evt
-,
-
.
,
Java,
getSource()
Object,
Java,
.
,
,
.
-
,
!
(we
cast
the
type)
Object
JButton,
:
Java , ,
JButton clickedButton =
103
(JButton) evt.getSource();
JButton
,
getSource()
Object,
JVM:
,
,
JButton.
Object
JButton
getText(),
JButton.
import
import
import
import
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
javax.swing.JOptionPane;
javax.swing.JButton;
,
,
:
Java , ,
104
,
,
-
?
JButton!
Java,
instanceof
,
.
,
,
JButton
JTextField:
public void actionPerformed(ActionEvent evt){
JTextField myDisplayField=null;
JButton clickedButton=null;
Object eventSource = evt.hetSource();
if (eventSource instanceof JButton){
clickedButton = (JButton) eventSource;
}else if (eventSource instanceof JTextField){
myDisplayField = (JTextField)eventSource;
}
,
,
.
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if (src == buttonPlus){
// ,
} else if (src == buttonMinus){
// ,
}else if (src == buttonDivide){
// -
} else if (src == buttonMultiply){
// ,
}
Java , ,
105
-,
,
,
.
displayField
Calculator
actionPerformed()
CalculatorEngine.
,
CalculatorEngine
,
Calculator.
CalculatorEngine
.
Calculator.
,
,
!
JVM
CalculatorEngine
.
Calculator
CalculatorEngine,
:
CalculatorEngine calcEngine = new CalculatorEngine(this);
,
Calculator.
CalculatorEngine
parent,
actionPerformed()
.
parent.displayField.getText();
parent.displayField.setText(dispFieldText + clickedButtonLabel);
:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener {
Calculator parent; // Calculator
//
// parent
CalculatorEngine(Calculator parent){
this.parent = parent;
Java , ,
106
}
public void actionPerformed(ActionEvent e){
//
JButton clickedButton = (JButton) e.getSource();
// ()
//
String dispFieldText = parent.displayField.getText();
//
String clickedButtonLabel = clickedButton.getText();
parent.displayField.setText(dispFieldText +
clickedButtonLabel);
}
-
,
,
,
.
Java
Object,
,
,
Fish
Pet,
:
Fish myFish
Pet myFish
= new Fish();
= new Fish();
(
),
:
1.
.
2.
-
+,
-,
/
or
*
,
,
.
3.
.
Java , ,
107
4.
double,
.
,
2.
5.
4
,
2.
CalculatorEngine.
,
,
actionPerformed()
selectedAction
currentResult.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener {
Calculator parent;
//
// +, -, /, *
//
//
CalculatorEngine(Calculator parent){
this.parent = parent;
}
public void actionPerformed(ActionEvent e){
//
JButton clickedButton =
(JButton) e.getSource();
String dispFieldText=parent.displayField.getText();
double displayValue=0;
// ,
// .
//
if (!"".equals(dispFieldText)){
displayValue= Double.parseDouble(dispFieldText);
Java , ,
108
}
Object src = e.getSource();
//
//
//
//
: +, -, /, *,
currentResult,
if (src == parent.buttonPlus){
selectedAction = '+';
currentResult=displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonMinus){
selectedAction = '-';
currentResult=displayValue;
parent.displayField.setText("");
}else if (src == parent.buttonDivide){
selectedAction = '/';
currentResult=displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonMultiply){
selectedAction = '*';
currentResult=displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonEqual){
// ,
// selectedAction, currentResult
//
if (selectedAction=='+'){
currentResult+=displayValue;
// ,
//
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='-'){
currentResult -=displayValue;
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='/'){
currentResult /=displayValue;
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='*'){
Java , ,
109
currentResult*=displayValue;
parent.displayField.setText(""+currentResult);
}
} else{
//
//
String clickedButtonLabel= clickedButton.getText();
parent.displayField.setText(dispFieldText +
clickedButtonLabel);
}
-
:
Calculator
:
.
CalculatorEngine.
CalculatorEngine
.
,
.
Calculator:
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
//
JButton button0=new JButton("0");
JButton button1=new JButton("1");
JButton button2=new JButton("2");
Java , ,
JButton
JButton
JButton
JButton
JButton
JButton
JButton
JButton
JButton
button3=new JButton("3");
button4=new JButton("4");
button5=new JButton("5");
button6=new JButton("6");
button7=new JButton("7");
button8=new JButton("8");
button9=new JButton("9");
buttonPoint = new JButton(".");
buttonEqual=new JButton("=");
JButton
JButton
JButton
JButton
buttonPlus=new JButton("+");
buttonMinus=new JButton("-");
buttonDivide=new JButton("/");
buttonMultiply=new JButton("*");
110
Java , ,
111
// GridLayout
// 4 // , ,
JPanel p2 = new JPanel();
GridLayout gl2 =new GridLayout(4,1);
p2.setLayout(gl2);
p2.add(buttonPlus);
p2.add(buttonMinus);
p2.add(buttonMultiply);
p2.add(buttonDivide);
// p2
windowContent.add("East",p2);
// frame
frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
JFrame
// ,
//
frame.pack();
//
frame.setVisible(true);
//
//
CalculatorEngine calcEngine = new CalculatorEngine(this);
button0.addActionListener(calcEngine);
button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
button5.addActionListener(calcEngine);
button6.addActionListener(calcEngine);
button7.addActionListener(calcEngine);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonPoint.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
buttonMinus.addActionListener(calcEngine);
buttonDivide.addActionListener(calcEngine);
buttonMultiply.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
}
public static void main(String[] args) {
//
Calculator calc = new Calculator();
}
Java , ,
112
Calculator.
,
.
!
,
.
,
,
,
.
,
Eclipse,
.
Java
java.awt,
:
(FocusListener)
,
.
,
,
,
.
(ItemListener)
.
(KeyListener)
.
(MouseListener)
,
,
.
(MouseMotionListener)
,
-
.
(drag)
.
(WindowListener)
,
,
,
.
,
,
.
Java , ,
113
Interface
Methods to implement
FocusListener
focusGained(FocusEvent)
focusLost(FocusEvent)
ItemListener
itemStateChanged(ItemEvent)
KeyListener
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
mouseClicked(MouseEvent)
MouseListener
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
WindowListener
(WindowEvent)
windowActivated
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated
(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
Java , ,
114
,
FocusListener
:
focusGained()
focusLost().
,
-
,
focusLost().
,
Java
-
,
.
,
-
,
.
,
,
WindowsListener
.
,
windowClosing()
.
java.awt
,
,
(,
).
WindowAdapter.
,
,
WindowAdapter
,
,
windowClosing().
class MyEventProcessor extends java.awt.WindowsAdapter {
public void windowClosing(WindowEvent e) {
// ,
//
}
}
,
:
MyEventProcessor myListener = new MyEventProcessor();
addWindowListener(myListener);
,
,
.
Java , ,
115
:
http://download.oracle.com/javase/tutorial/uiswing/events/
-
Infinity.
CalculatorEngine,
,
,
.
CalculatorEngine
,
.
:
indexOf()
String,
,
.
Java , ,
116
7. -
,
Java
.
-.
-
,
HTML,
()
,
.
,
HTML
<applet>,
,
Java.
Java-
,
-,
,
JVM
,
.
,
,
,
-
Java , ,
117
,
.
,
,
-
Java
,
,
-
,
-
.
:
,
,
.
,
.
.
,
Java,
HTML,
<applet>,
,
-,
Java.
Eclipse
,
appletviewer.
,
15
,
HTML.
HTML 15
,
-
-
(TicTacToe).
HTML
.
TicTacToe.html
(,
Eclipse
).
HTML
.html
.htm.
(header)
(body).
HTML
,
(/),
<Head>
</Head>.
TicTacToe.html
:
<HTML>
<HEAD>
<TITLE>My First Web Page</TITLE>
Java , ,
118
</HEAD>
<BODY>
My Tic-Tac-Toe game is coming soon
</BODY>
</HTML>
,
<Title>
</Title>,
.
HTML
-
Java,
,
.
-
.
My
First
Web
Page,
My
Tic-Tac-Toe
game
is
coming
soon:
,
-:
<HTML>
<BODY>
Here is my Tic-Tac-Toe game:
<APPLET code=TicTacToe.class width=300 height=250>
</APPLET>
</BODY>
</HTML>
-:
Java , ,
119
:
-
TicTacToe,
.
.
HTML
,
.
<APPLET>
:
code
-
Java-.
width
,
.
,
.
height
-
,
.
Java-
,
jar,
JDK
(Java
Developer
Kit
Java).
,
(archive)
,
.
jar
.
Java , ,
120
A AWT
AWT
,
,
Swing
?
,
Swing?
,
.
-
JVM,
AWT,
Swing,
.
,
JVM,
HTML,
HTML
,
JVM,
?
,
,
,
.
-
,
,
.
,
-,
(
).
AWT,
,
.
,
.
Java
.
JVM,
JVM,
.
,
(
)
JVM
.
:
https://jdk6.dev.java.net/plugin2
.
Microsoft
Windows
Java
Control
Panel
-
Java
Start
|
Control
Panel.
Advanced
Java
Plug-in
,
Enable
the
next-generation
Java
Plug-
in.
:
http://blogs.sun.com/thejavatutorials/entry/enabling_the_next_generation_j
ava
.
Java , ,
121
, Swing
. Java
. JavaFX , ,
: http://javafx.com/.
Java-
AWT
java.applet.Applet,
:
class TicTacToe extends java.applet.Applet {
}
Swing,
JApplet:
class TicTacToe extends javax.swing.JApplet {
}
Java,
main(),
-
,
<applet>.
,
,
,
,
.
,
,
(callback
methods):
init(), start(), paint(), stop(),
destroy().
JVM
-
:
init()
,
.
,
,
Java.
start()
init().
,
.
Java , ,
122
paint()
,
-
.
,
-
.
stop()
,
-
,
.
destroy()
,
.
,
,
,
,
.
,
:
init()
paint().
,
,
!.
paint()
,
Graphics
JVM
-.
.
drawString(),
,
!.
public class HelloApplet extends java.applet.Applet {
public void paint(java.awt.Graphics graphics) {
graphics.drawString(", !", 70, 40);
}
Eclipse.
Run
Java
Applet
,
New,
HelloApplet
Applet
Class.
-,
Hello.html
,
:
<HTML>
<BODY>
Here is my first applet:<P>
<APPLET code=HelloApplet.class width=200 height=100>
</APPLET>
</BODY>
</HTML>
Java , ,
123
-
Hello.html
File
Open.
:
,
?
!
Java , ,
124
-
,
.
.
,
,
.
,
.
-
,
:
3x3.
,
.
,
,
.
,
.
,
.
,
.
,
New
Game.
,
,
,
,
,
.
,
,
,
,
.
,
,
,
.
Java , ,
125
,
,
,
.
BorderLayout,
New
Game.
,
,
:
init().
ActionListener
actionPerformed().
lookForWinner()
,
,
.
computerMove(),
.
Java
Math
random().
,
,
:
if(squares[0].getLabel().equals(squares[1].getLabel())){}
Java , ,
126
,
,
:
String label0 = squares[0].getLabel();
String label1 = squares[1].getLabel();
if(label0.equals(label1)){}
Java
,
.
,
equals(),
getLabel().
,
.
.
/**
* - 3x3
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class TicTacToe extends Applet implements ActionListener{
Button squares[];
Button newGameButton;
Label score;
int emptySquaresLeft=9;
/**
* init
*/
public void init(){
// ,
this.setLayout(new BorderLayout());
this.setBackground(Color.CYAN);
// ,
// 20
Font appletFont=new Font("Monospased",Font.BOLD, 20);
this.setFont(appletFont);
// New Game
//
Java , ,
newGameButton=new Button("New Game");
newGameButton.addActionListener(this);
Panel topPanel=new Panel();
topPanel.add(newGameButton);
this.add(topPanel,"North");
Panel centerPanel=new Panel();
centerPanel.setLayout(new GridLayout(3,3));
this.add(centerPanel,"Center");
score=new Label("Your turn!");
this.add(score,"South");
// , 9
squares=new Button[9];
// ,
// ,
//
for(int i=0;i<9;i++){
squares[i]=new Button();
squares[i].addActionListener(this);
squares[i].setBackground(Color.ORANGE);
centerPanel.add(squares[i]);
}
}
/**
*
* @param ActionEvent
*/
public void actionPerformed(ActionEvent e) {
Button theButton = (Button) e.getSource();
// New Game ?
if (theButton ==newGameButton){
for(int i=0;i<9;i++){
squares[i].setEnabled(true);
squares[i].setLabel("");
squares[i].setBackground(Color.ORANGE);
}
emptySquaresLeft=9;
score.setText("Your turn!");
newGameButton.setEnabled(false);
127
Java , ,
return;
128
//
theButton == squares[i] ) {
squares[i].setLabel("X");
winner = lookForWinner();
if(!"".equals(winner)){
endTheGame();
} else {
computerMove();
winner = lookForWinner();
if ( !"".equals(winner)){
endTheGame();
}
break;
}
} // for
if ( winner.equals("X") ) {
score.setText("You won!");
} else if (winner.equals("O")){
score.setText("You lost!");
} else if (winner.equals("T")){
score.setText("It's a tie!");
}
} // actionPerformed
/**
*
*
*
*
*
*/
, ,
. ,
,
( )
@return "X", "O", "T" , "" -
String lookForWinner() {
String theWinner = "";
emptySquaresLeft--;
Java , ,
if (emptySquaresLeft==0){
return "T"; // . T tie
}
// 1 0,1,2
if (!squares[0].getLabel().equals("") &&
squares[0].getLabel().equals(squares[1].getLabel()) &&
squares[0].getLabel().equals(squares[2].getLabel())) {
theWinner = squares[0].getLabel();
highlightWinner(0,1,2);
// 2 3,4,5
} else if (!squares[3].getLabel().equals("")
&&
squares[3].getLabel().equals(squares[4].getLabel()) &&
squares[3].getLabel().equals(squares[5].getLabel())) {
theWinner = squares[3].getLabel();
highlightWinner(3,4,5);
// 3 6,7,8
} else if ( ! squares[6].getLabel().equals("") &&
squares[6].getLabel().equals(squares[7].getLabel()) &&
squares[6].getLabel().equals(squares[8].getLabel())) {
theWinner = squares[6].getLabel();
highlightWinner(6,7,8);
// 1 0,3,6
} else if ( ! squares[0].getLabel().equals("") &&
squares[0].getLabel().equals(squares[3].getLabel()) &&
squares[0].getLabel().equals(squares[6].getLabel())) {
theWinner = squares[0].getLabel();
highlightWinner(0,3,6);
// 2 1,4,7
} else if ( ! squares[1].getLabel().equals("") &&
squares[1].getLabel().equals(squares[4].getLabel()) &&
squares[1].getLabel().equals(squares[7].getLabel())) {
theWinner = squares[1].getLabel();
highlightWinner(1,4,7);
// 3 2,5,8
} else if ( ! squares[2].getLabel().equals("") &&
squares[2].getLabel().equals(squares[5].getLabel()) &&
squares[2].getLabel().equals(squares[8].getLabel())) {
129
Java , ,
theWinner = squares[2].getLabel();
highlightWinner(2,5,8);
// 0,4,8
} else if ( ! squares[0].getLabel().equals("") &&
squares[0].getLabel().equals(squares[4].getLabel()) &&
squares[0].getLabel().equals(squares[8].getLabel())) {
theWinner = squares[0].getLabel();
highlightWinner(0,4,8);
// 2,4,6
} else if ( ! squares[2].getLabel().equals("") &&
squares[2].getLabel().equals(squares[4].getLabel()) &&
squares[2].getLabel().equals(squares[6].getLabel())) {
theWinner = squares[2].getLabel();
highlightWinner(2,4,6);
return theWinner;
}
/**
* ,
* .
* , .
*/
void computerMove() {
int selectedSquare;
//
// ,
selectedSquare = findEmptySquare("O");
//
//
//
if
,
3-
,
( selectedSquare == -1 )
selectedSquare =
findEmptySquare("X");
}
// selectedSquare -1,
//
if ( (selectedSquare == -1)
&&(squares[4].getLabel().equals("")) ){
selectedSquare=4;
}
130
Java , ,
131
// ...
//
if ( selectedSquare == -1 ){
selectedSquare = getRandomSquare();
}
squares[selectedSquare].setLabel("O");
/**
* ,
* ,
* .
* @param
X O
* @return ,
*
-1,
*
*/
int findEmptySquare(String player) {
int weight[] = new int[9];
for ( int i = 0; i < 9; i++ ) {
if ( squares[i].getLabel().equals("O") )
weight[i] = -1;
else if ( squares[i].getLabel().equals("X") )
weight[i] = 1;
else
weight[i] = 0;
}
int twoWeights = player.equals("O") ? -2 : 2;
// , 1
// .
if ( weight[0] + weight[1] + weight[2] == twoWeights ) {
if ( weight[0] == 0 )
return 0;
else if ( weight[1] == 0 )
return 1;
else
return 2;
}
// , 2
// .
if (weight[3] +weight[4] + weight[5] == twoWeights) {
if ( weight[3] == 0 )
return 3;
else if ( weight[4] == 0 )
return 4;
else
return 5;
}
Java , ,
// , 3
// .
if (weight[6] + weight[7] +weight[8] == twoWeights ) {
if ( weight[6] == 0 )
return 6;
else if ( weight[7] == 0 )
return 7;
else
return 8;
// , 1
// .
if (weight[0] + weight[3] + weight[6] == twoWeights) {
if ( weight[0] == 0 )
return 0;
else if ( weight[3] == 0 )
return 3;
else
return 6;
}
// , 2
// .
if (weight[1] +weight[4] + weight[7] == twoWeights ) {
if ( weight[1] == 0 )
return 1;
else if ( weight[4] == 0 )
return 4;
else
return 7;
// , 3
// .
if (weight[2] + weight[5] + weight[8] == twoWeights ){
if ( weight[2] == 0 )
return 2;
else if ( weight[5] == 0 )
return 5;
else
return 8;
}
// , 1
// .
if (weight[0] + weight[4] + weight[8] == twoWeights ){
132
Java , ,
if ( weight[0] == 0 )
return 0;
else if ( weight[4] == 0 )
return 4;
else
return 8;
// , 2
// .
if (weight[2] + weight[4] + weight[6] == twoWeights ){
if ( weight[2] == 0 )
return 2;
else if ( weight[4] == 0 )
return 4;
else
return 6;
}
//
return -1;
} // findEmptySquare()
/**
*
* @return
*/
int getRandomSquare() {
boolean gotEmptySquare = false;
int selectedSquare = -1;
do {
selectedSquare = (int) (Math.random() * 9 );
if (squares[selectedSquare].getLabel().equals("")){
gotEmptySquare = true; //
}
} while (!gotEmptySquare );
return selectedSquare;
} // getRandomSquare()
/**
* .
* @param ,
*/
void highlightWinner(int win1, int win2, int win3) {
133
Java , ,
134
squares[win1].setBackground(Color.CYAN);
squares[win2].setBackground(Color.CYAN);
squares[win3].setBackground(Color.CYAN);
}
// New Game
void endTheGame(){
newGameButton.setEnabled(true);
for(int i=0;i<9;i++){
squares[i].setEnabled(false);
}
}
} //
!
Java!
Swing, Button
JButton, Panel JPanel, .. ,
-, :
http://download.oracle.com/javase/tutorial/deployment/applet.
Eclipse,
TicTacToe.html,
,
TicTacToe.html
TicTacToe.class
.
TicTacToe
,
,
,
,
.
TicTacToe
,
,
,
,
.
,
.
Java:
http://download.oracle.com/javase/tutorial/deployment/
applet/
Java , ,
135
Math
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Math.
html
1.
TicTacToe
.
,
.
,
You
won
You
lost.
2.
,
.
!
,
.
,
.
3.
main()
TicTacToe,
,
Java-.
Java , ,
136
1.
TicTacToe,
,
JButton squares[]
3x3:
JButton squares[][]
2.
.
Java , ,
137
8.
, Java-.
,
.
(run-time
errors),
,
,
.
,
Java-
.
,
-
?
,
,
,
:
, - ,
scores.txt.
,
,
?
,
.
.
Java
,
.
Java
(exceptions),
(exception
handling).
,
,
try/catch.
JVM
:
,
-
,
,
:
try{
fileScores.read();
} catch (IOException e){
System.out.println(
" ,
Java , ,
138
scores.txt");
}
9,
I/O
/
(input/output).
(
)
/,
IOException
,
/.
(throws)
.
.
catch
,
catch.
,
,
.
,
,
.
,
,
.
(stack
trace).
,
,
,
.
TestStackTrace,
(
).
1 class TestStackTrace{
2
TestStackTrace()
3
{
4
divideByZero();
5
}
6
7
int divideByZero()
8
{
9
return 25/0;
10
}
11
12
static void main(String[]args)
13
{
14
new TestStackTrace();
15
}
16 }
Java , ,
139
,
.
,
.
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at TestStackTrace.divideByZero(TestStackTrace.java:9)
at TestStackTrace.<init>(TestStackTrace.java:4)
at TestStackTrace.main(TestStackTrace.java:14)
,
main(),
init()
,
divideByZero().
14,
4
9
,
.
,
ArithmeticException,
9
.
Java
,
(
):
Java , ,
140
Exception
(checked
exceptions),
.
..
-
,
,
.
Error
JVM,
.
TooManyBikesException (
)
,
.
,
Java-
,
Java , ,
141
try/catch?
!
,
,
Java
,
:
"ScoreReader.java": unreported exception:
java.io.IOException; must be caught or declared to be
thrown at line 57
,
,
Java.
.
try/catch
Java
: try, catch, finally, throw throws.
try
catch,
,
.
,
,
,
FileNotFoundException.
,
,
,
EOFException.
,
.
.
public void getScores(){
try{
fileScores.read();
System.out.println(" ");
}catch(FileNotFoundException e){
System.out.println(" Scores");
}catch(EOFException e1){
System.out.println(" ");
}catch(IOException e2){
System.out.println(" " +
e2.getMessage());
}
}
Java , ,
142
read()
,
println()
catch
.
,
println(),
catch
,
getScores()
,
.
catch,
,
,
.
,
EOFException
IOException,
catch
.
catch
IOException,
FileNotFound
EOFException,
catch
.
Java 7,
catch:
public void getScores(){
try{
fileScores.read();
System.out.println(" ");
}catch(FileNotFoundException | EOFException |
IOException e){
System.out.println(" " +
e.getMessage());
}
}
getScores()
:
public void getScores(){
try{
fileScores.read();
}catch(Exception e){
System.out.println((" " +
e.getMessage());
}
.
,
,
-
,
.
Java , ,
143
catch
Exception,
,
getMessage()
.
,
,
toString():
catch(Exception e){
System.out.println(" " + e.toString());
}
,
printStackTrace().
,
,
,
.
6.
Calculator
abc.
-
:
java.lang.NumberFormatException: For input string: "abc" at
java.lang.NumberFormatException.forInputString(NumberFormat
Exception.java:48)
at
java.lang.FloatingDecimal.readJavaFormatString(FloatingDeci
mal.java:1213)
at java.lang.Double.parseDouble(Double.java:202)
at
CalculatorEngine.actionPerformed(CalculatorEngine.java:27)
at
javax.swing.AbstractButton.fireActionPerformed(AbstractButt
on.java:1764)
.
actionPerformed()
CalculatorEngine
:
displayValue= Double.parseDouble(dispFieldText);
dispFieldTest
,
parseDouble()
double
NumberFormatException.
Java , ,
144
,
. ,
parseDouble()
try/catch,
Eclipse
.
. Source
and
Surround
with
try/catch
block.
!
:
try {
displayValue= Double.parseDouble(dispFieldText);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
printStackTrace() :
javax.swing.JOptionPane.showConfirmDialog(null,
", ", " ",
javax.swing.JOptionPane.PLAIN_MESSAGE);
return;
, :
NumberFormatException
.
throws
,
,
,
,
e
.
Java , ,
145
,
(),
.
throws.
.
read()
IOException,
,
.
,
getAllScores()
IOException:
class MySuperGame{
getAllScores(),
IOException
main().
.
finally
try/catch
:
Java , ,
146
try
,
.
try
return
.
try
,
catch,
,
,
.
,
,
finally:
try{
file.read();
}catch(Exception e){
printStackTrace();
}finally{
// ,
// , file.close();
}
finally,
,
.
,
finally
,
-
,
,
.
,
.
,
finally
catch:
void myMethod () throws IOException{
try{
}
// ,
finally{
// ,
}
Java , ,
147
throw
,
,
.
,
,
,
.
throw
()
()
Java-.
,
,
.
,
,
Throwable.
Java
.
getAllScores()
IOException,
Exception
main().
,
main()
,
getAllScores()
try/catch,
Exception,
,
,
.
main()
,
.
class ScoreList{
//
Java , ,
148
,
,
e1.getMessage()
,
,
,
Java.
Java , ,
149
.
,
.
,
.
,
FireBird.
Exception
TooManyBikesException.
,
-
,
:
class TooManyBikesException extends Exception{
//
TooManyBikesException (){
//
// ,
super(
" .");
}
}
,
,
.
.
catch
,
,
,
getMessage().
,
OrderWindow
.
,
actionPerformed(),
,
.
,
checkOrder()
,
TooManyBikesException.
,
,
catch.
.
class OrderWindow implements ActionListener{
// .
//
String selectedModel = txtFieldModel.getText();
String selectedQuantity = txtFieldQuantity.getText();
int quantity = Integer.parseInt(selectedQuantity);
Java , ,
150
.
.
,
Java
,
,
.
:
http://download.oracle.com/javase/tutorial/ess
ential/exceptions/index.html
Java , ,
151
1.
Swing-
.
,
.
2.
OrderWindow
TooManyBikesException.
,
.
1.
,
,
,
,
.
2.
Swing-
JComboBox
ItemListener
,
.
Java , ,
152
9.
, ,
.
,
,
,
.
,
,
,
,
.
,
,
(streams).
,
(
,
).
,
,
,
.
,
,
scores.txt,
.
,
,
..
,
,
String,
int,
double
,
Java,
,
,
,
.
java.io.
java.nio.
,
,
:
,
.
.
.
Java , ,
153
,
,
,
,
.
,
,
,
,
-
,
.
,
,
Java
FileInputStream FileOutputStream.
,
FileInputStream
abc.gif
c:\practice.
Microsoft
Windows,
Java,
,
:
c:\\practice.
,
,
,
.
0
255.
ByteReader
,
.
,
ByteReader
finally.
close()
try/catch
,
finally.
,
close()
!
,
FileInputStream.read()
.
import java.io.FileInputStream;
import java.io.IOException;
public class ByteReader {
public static void main(String[] args) {
FileInputStream myFile = null;
try {
// ,
myFile = new FileInputStream("c:\\temp\\abc.gif");
Java , ,
154
while (true) {
int intValueOfByte = myFile.read();
System.out.print(" " + intValueOfByte);
if (intValueOfByte
== -1){
//
break;
}
} // while
// myFile.close();
} catch (IOException e) {
System.out.println(" : "
+ e.toString());
} finally{
try{
myFile.close();
} catch (Exception e1){
e1.printStackTrace();
System.out.println(
" ");
}
,
,
xyz.dat,
FileOutputStream:
int somedata[]= {56,230,123,43,11,37};
FileOutputStream myFile = null;
try {
// xyz.dat,
//
myFile = new
FileOutputStream("xyz.dat");
Java , ,
155
}
} catch (IOException e) {
System.out.println(" : "+
e.toString());
} finally{
try{
myFile.close();
} catch (Exception e1){
e1.printStackTrace();
}
,
.
,
1000
,
ByteReader
1000
.
,
.
,
Java
,
"
".
BufferedInputStream
FileInputStream.
,
read()
.
,
,
.
,
.
,
FileInputStream
BufferedInputStream,
read():
FileInputStream myFile = null;
BufferedInputStream buff =null;
try {
myFile = new
FileInputStream("abc.dat");
Java , ,
156
// FileInputStream BufferedInputStream
buff = new BufferedInputStream(myFile);
while (true) {
int byteValue = buff.read();
System.out.print(byteValue + " ");
if (byteValue
break;
== -1)
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
buff.close();
myFile.close();
} catch(IOException e1){
e1.printStackTrace();
}
?
JVM,
600
,
.
,
5000
,
:
BufferedInputStream buff = new BufferedInputStream(myFile, 5000);
,
.
BufferedOutputStream
,
,
,
FileOutputStream.
int somedata[]= {56,230,123,43,11,37};
FileOutputStream myFile = null;
BufferedOutputStream buff =null;
try {
myFile = new
FileOutputStream("abc.dat");
//
buff = new BufferedOutputStream(myFile);
for (int i = 0; i <somedata.length; i++){
Java , ,
157
buff.write(somedata[i]);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
buff.flush();
buff.close();
myFile.close();
} catch(IOException e1){
e1.printStackTrace();
}
,
,
BufferedOutputStream,
flush().
ByteReader
abc.gif
,
,
,
(
)
.
,
,
xyz.gif,
,
.
,
.
Java
,
:
java ByteReader xyz.gif
main()
xyz.gif.
,
main()
:
public static void main(String[] args) {}
,
String,
JVM
.
,
Java , ,
158
.
,
,
.
,
,
:
public class TestArguments {
,
,
xyz.gif
250.
JVM
xyz.gif
args[0],
args[1].
(String).
,
:
int myScore = Integer.parseInt(args[1]);
,
.
main().
,
,
System.exit():
public static void main(String[] args) {
if (args.length != 2){
Java , ,
159
System.out.println(
", , :");
System.out.println("java TestArguments xyz.gif 250");
//
System.exit(0);
}
.
,
,
.
Eclipse,
,
.
Run
Configurations,
(x)=Arguments
Program
Arguments.
Java , ,
160
VM
arguments
JVM.
,
,
,
JVM,
..
.
Java
,
FileReader
FileWriter
.
,
read(),
,
readLine().
FileReader
FileWriter
Java , ,
161
,
BufferedReader BufferedWriter,
.
ScoreReader
scores.txt
.
,
readLine()
null,
.
,
c:\scores.txt,
:
David 235
Brian 190
Anna 225
Zachary 160
ScoreReader,
.
.
,
,
.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ScoreReader {
public static void main(String[] args) {
FileReader myFile = null;
BufferedReader buff = null;
try {
myFile=new FileReader("c:\\scores.txt");
buff = new BufferedReader(myFile);
while (true) {
// scores.txt
String line = buff.readLine();
//
if (line == null) break;
System.out.println(line);
} // while
Java , ,
162
} // main
,
write()
FileWriter.
,
String
.
FileWriter
(overloaded)
.
,
,
:
FileWriter fOut = new FileWriter("Scores.txt");
,
(true
,
):
,
ScoreWriter
scores
c:\scores.txt.
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class ScoreWriter {
public static void main(String[] args) {
FileWriter myFile = null;
BufferedWriter buff = null;
String[] scores = new String[3];
Java , ,
163
//
scores[0] = "Mr. Smith 240";
scores[1] = "Ms. Lee 300";
scores[2] = "Mr. Dolittle 190";
try {
myFile = new FileWriter("c:\\scores2.txt");
buff = new BufferedWriter(myFile);
for (int i=0; i < scores.length; i++) {
// scores2.txt
buff.write(scores[i]);
System.out.println("
" + scores[i] );
}
System.out.println(" ");
}catch (IOException e){
e.printStackTrace();
} finally {
try{
buff.flush();
buff.close();
myFile.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
} // main
Java , ,
164
File
java.io.File
,
,
,
..
,
,
.
,
File,
,
exists().
true,
abc.txt
,
:
File aFile = new File("abc.txt");
if (aFile.exists()){
// a JOptionPane
//
}
File,
,
,
.
,
createNewFile().
File.
createNewFile()
delete()
,
File.
,
.
renameTo()
length()
exists()
true,
list()
Java , ,
165
/,
lastModified()
mkDir()
customers.txt
customers.txt.bak.
.bak
,
.
File file = new File("customers.txt");
File backup = new File("customers.txt.bak");
if (backup.exists()){
backup.delete();
}
file.renameTo(backup);
Java
7
Files,
,
.
File,
Files
,
.
Path
,
.
Customers.txt
Windows
:
Path pathCustomers=
FileSystems.getDefault().getPath(.,c\\Customers.txt);
Path pathCustomers=
FileSystems.getDefault().getPath(.,/Customers.txt);
:
List customers=
Files.readAllLines(pathCustomers,Charset.defaultCharset());
,
:
byte[] customers=Files.readAllBytes(pathCustomers);
:
Reader reader=
Files.newBufferedReader(pathCustomers, Charset.defaultCharset());
Java , ,
166
Customers.txt
:
Path fileName= Paths.get(c:\\Customers.txt);
Path customers=Paths.createFile(fileName);
,
Java
,
.
.
,
NASA
Java
.
,
.
J
1.
JVM
http://download.oracle.com/javase/tutorial/essential/environm
ent/cmdLineArgs.html
2.
http://java.sun.com/docs/books/tutorial/essential/io/filestreams
.html
Java , ,
167
FileCopy,
.
(
)
read()
write()
.
,
:
java FileCopy c:\\temp\\scores.txt
c:\\backup\\scores2.txt
Swing,
,
JFileChooser,
.
Browse.
.
,
Copy,
actionPerformed()
.
Java , ,
168
,
/.
Java , ,
169
10.
Java
.
-.
,
Java
.
.
Java
,
.
,
15.06.2011
15
2011.
Java
,
.
java.util.Date
java.text.SimpleDateFormat
.
,
:
Date today = new Date();
System.out.println( ": " + today );
:
: Sat Oct 08 20:41:44 MSD 2011
SimpleDateFormat
.
,
.
format(),
Java , ,
170
Date.
.
import java.util.Date;
import java.text.SimpleDateFormat;
public class MyDateFormat {
public static void main( String [] args ) {
// Date
//
Date today = new Date();
System.out.println( ": " + today );
// , 10-08-11
SimpleDateFormat sdf= new SimpleDateFormat("MM-dd-yy");
String formattedDate=sdf.format(today);
System.out.println( "(--): " + formattedDate );
// , 08-10-2011
sdf = new SimpleDateFormat("dd-MM-yyyy");
formattedDate=sdf.format(today);
System.out.println( "(--): " + formattedDate );
// , , 27, 11
sdf = new SimpleDateFormat("EEE, MMM d, ''yy");
formattedDate=sdf.format(today);
System.out.println(
" ( , , ') "+ formattedDate);
// , 07:18:51 AM
sdf = new SimpleDateFormat("hh:mm:ss a");
formattedDate=sdf.format(today);
System.out.println( " (::) "+ formattedDate );
}
MyDateFormat,
-
:
: Sat Oct 08 20:54:37 MSD 2011
(--): 10-08-11
(--): 08-10-2011
Java , ,
171
( , , ') , 8, '11
(::) 08:54:37 PM
Java
SimpleDateFormat
.
,
,
Java
java.util.Calendar.
,
.
(method
overloading).
,
println()
System
:
String,
int,
char
.
System.out.println("!");
System.out.println(250);
System.out.println('A');
,
println(),
.
,
,
,
printString(),
printInt(),
printChar()?
,
,
.
,
,
.
(polymorfism)
.
,
Fish
4,
dive(),
:
public int dive(int howDeep)
,
.
5
,
100
.
Fish
final
DEFAULT_DIVING
(
),
.
Java , ,
172
Fish
dive().
public class Fish extends Pet {
int currentDepth=0;
final int DEFAULT_DIVING = 5;
public int dive(){
currentDepth=currentDepth + DEFAULT_DIVING;
if (currentDepth > 100){
System.out.println(" " +
" 100 ");
currentDepth=currentDepth - DEFAULT_DIVING;
}else{
System.out.println(" " +
DEFAULT_DIVING + " ");
System.out.println(" " + currentDepth +
" ");
}
return currentDepth;
Java , ,
173
FishMaster
dive():
public class FishMaster {
public static void main(String[] args) {
Fish myFish = new Fish(20);
myFish.dive(2);
myFish.dive();
//
myFish.dive(97);
myFish.dive(3);
myFish.sleep();
}
,
.
JVM
.
,
Fish
(
),
FishMaster
:
Fish myFish = new Fish(20);
Fish myFish = new Fish();
Java , ,
174
,
,
.
FishMaster
,
Fish.
:
?,
.
System.out.
,
out
java.io.OutputStream.
,
System.in.
,
,
,
in
java.io.InputStream.
FishMaster
.
,
Enter,
JVM
InputStream
.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class FishMaster {
public static void main(String[] args) {
Fish myFish = new Fish(20);
String feetString="";
int feet;
// InputStreamReader,
// System.in
// BufferedReader
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
//
// "Q"
while (true) {
System.out.println(" . ?");
Java , ,
175
try {
feetString = stdin.readLine();
if (feetString.equals("Q")){
//
System.out.println("!");
System.exit(0);
}else {
// feetString
// , feet
feet = Integer.parseInt(feetString);
myFish.dive(feet);
}
} catch (IOException e) {
e.printStackTrace();
}
} // while
} // main
FishMaster
:
. ?
14
14 .
34 .
. ?
30
30 .
64 .
. ?
Q
!
FishMaster
BufferedReader,
System.in.
Java , ,
176
.
?
readLine()
,
Enter.
String,
FishMaster
int
dive()
Fish.
,
Q,
.
feetString.equals("Q")
feetString
String
Q.
,
,
readLine().
System.in.read(),
,
,
.
,
,
,
,
.
,
,
(),
.
Java
.
,
java.io
,
/.
javax.swing
Swing.
Eclipse
PingPong.
:
screens
engine.
PingPongTable
Package
screens:
Java , ,
177
Finish
()
Eclipse
,
.
package screens;
public class PingPongTable {
public static void main(String[] args) {
}
Java , ,
178
,
package,
.
,
Eclipse
screens
PingPongTable.java.
c:\eclipse\workspace\PingPong\screens
PingPongTable.java
PingPongTable.class.
PingPongEngine,
engine.
PingPong
:
Java , ,
179
(,
,
),
PingPongTable
PingPongEngine,
import.
package screens;
import engine.PingPongEngine;
public class PingPongTable {
public static void main(String[] args) {
PingPongEngine gameEngine = new PingPongEngine();
}
Java
.
,
.
Java,
: public, private, protected
package.
Java , ,
180
PingPongEngine
public.
,
.
public
PingPongEngine.
PingPongTable
,
PingPongEngine
cannot
be
resolved
to
a
type
(
PingPongEngine)
The
type
engine.PingPongEngine
is
not
visible
(
engine.PingPongEngine
).
,
PingPongTable
PingPongEngine.
,
package.
,
,
().
,
PingPongEngine,
PingPongTable
,
,
.
-
,
.
private
.
.
,
,
,
,
.
.
Java
,
Car
public
brake(),
,
.
Java , ,
181
,
,
.
,
Java
,
,
.
public class Car {
// private
//
private String brakesCondition;
// public brake() private ,
// ,
public void brake(int pedalPressure){
boolean useRegularBrakes;
useRegularBrakes=checkForAntiLockBrakes (pedalPressure);
if (useRegularBrakes==true){
useRegularBrakes();
}else{
useAntiLockBrakes();
}
// private , -
//
private boolean checkForAntiLockBrakes(int pressure){
if (pressure > 100){
return true;
}else {
return false;
}
}
// private
//
private void useRegularBrakes(){
// ,
}
Java , ,
182
// private
//
private void useAntiLockBrakes(){
// ,
Java
protected
.
,
-
,
,
.
,
.
-
.
.
,
.
,
,
.
Java , ,
183
Score,
private.
9
ScoreWriter
String
.
,
.
.
,
,
.
Score.
(getter)
(setter)
,
private.
,
,
,
,
:
Score.score = 250;
:
Score.setScore(250);
,
,
,
500
?
Score
setScore(),
,
.
,
.
setScore()
.
,
.
?
.
,
setter-
,
.
import java.util.Date;
Java , ,
String firstName;
String lastName;
int score;
Date playDate;
184
Java , ,
185
// ,
// System.out.println(myScore.toString());
public String toString(){
String scoreString = firstName + " " +
lastName + " " + score + " " + playDate +
System.getProperty("line.separator");
return scoreString;
}
}
ScoreWriter2
Score
.
import
import
import
import
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;
java.util.Date;
Java , ,
186
scores[2].setLastName("");
scores[2].setScore(190);
scores[2].setPlayDate(today);
try {
myFile = new FileWriter("c:\\scores2.txt");
buff = new BufferedWriter(myFile);
for (int i=0; i < scores.length; i++) {
// String
// scores2.txt
buff.write(scores[i].toString());
System.out.println(" " +
scores[i].getLastName() );
System.out.println(" ");
}catch (IOException e){
e.printStackTrace();
} finally {
try{
buff.flush();
buff.close();
myFile.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}
,
,
,
scores[5].getLastName(),
Java
ArrayIndexOutOfBoundsException.
ArrayList
java.util
,
,
()
.
:
ArrayList,
HashTable,
HashMap
List.
,
java.util.ArrayList.
Java , ,
187
,
.
,
,
:
String[] myFriends = new String[5];
ArrayList
,
,
.
,
.
?
ArrayList!
,
.
ArrayList
,
.
,
,
int (
-
-
autoboxing).
ArrayList,
.
,
ArrayList,
add().
,
ArrayList
String
.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// ArrayList
ArrayList friends = new ArrayList();
friends.add("");
friends.add("");
friends.add("");
friends.add("");
// ?
int friendsCount = friends.size();
// ArrayList
for (int i=0; i<friendsCount; i++){
System.out.println(" " + i + " "+friends.get(i));
}
}
Java , ,
0
1
2
3
188
get()
ArrayList
,
.
,
get()
Object.
.
,
friends
String.
Java
Object
String.
,
ArrayList
,
,
Fish,
Fish
,
FishTank,
.
Fish,
,
ArrayList
fishTank.
,
Fish
.
import java.util.ArrayList;
public class FishTank {
public static void main(String[] args) {
ArrayList fishTank = new ArrayList();
Fish theFish;
Fish aFish = new Fish(20);
aFish.color = "";
aFish.weight = 2;
fishTank.add(aFish);
aFish = new Fish(10);
aFish.color = "";
aFish.weight = 5;
fishTank.add(aFish);
Java , ,
189
FishTank:
2.0 . :20
5.0 . :10
,
Java,
Pet
Fish.
age,
color,
weight
height
protected,
,
-
.
currentDepth
private.
public
,
,
getAge(),
age,
setAge(),
.
.
,
.
Score
private ,
getter-
setter-
.
Java,
,
,
.
Java.
,
.
Java , ,
190
1.
Java:
http://download.oracle.com/javase/tutorial/col
lections/intro/index.html
2.
ArrayList:
http://download.oracle.com/javase/7/docs/api
/java/util/ArrayList.html
3.
:
http://www.vogella.de/articles/JavaDateTimeA
PI/article.html
4.
Calendar:
http://download.oracle.com/javase/7/docs/api
/java/util/Calendar.html
1.
(
)
Fish.
10
.
FishMaster
Fish
,
:
Fish myFish = new Fish();
2.
Score
.
ScoreWriter3,
Score
setter-,
,
:
Score
aScore
new
Score("",
Java , ,
191
HashMap.
HashMapDemo,
ArrayListDemo,
.
Java , ,
192
11. .
-
5, 6 7
AWT
Swing
.
,
,
,
.
,
,
.
,
-.
,
.
,
(
)
21
.
.
.
N
,
Q
S
.
.
,
,
,
.
Java , ,
193
,
.
,
.
,
.
,
,
.
,
.
,
.
,
,
.
,
.
,
(
),
,
(
).
1.
?
(/)?
.
2.
,
(/)?
.
3.
(/)?
.
4.
(/)?
.
!
.
:
PingPongGreenTable
.
,
.
Java , ,
194
PingPongGameEngine,
,
,
.
PingPongGreenTable,
.
GameConstants
,
,
,
..
-:
:
-.
,
.
.
PingPongGreenTable,
JPanel
Swing.
,
.
Java , ,
195
,
PingPongGreenTable
-
PingPongGameEngine.
,
.
addPaneltoFrame()
,
.
,
paint(),
paintComponent().
JVM,
,
,
repaint().
,
,
repaint()
paintComponent()
Graphics,
.
.
,
,
fillRect().
X
Y
,
.
fillOval(),
,
.
,
.
X
,
Y
.
,
100
,
70:
X
Y
.
getPreferredSize().
,
,
Dimension
Swing.
Java
,
getPreferredSize()
Java , ,
196
PingPongGreenTable.
Dimension,
.
PingPongGreenTable
PingPongGameEngine
,
.
,
PingPongGreenTable
,
PingPongGameEngine
,
,
.
(
final)
.
GameConstants.
,
implements
GameConstants
final
,
!
PingPongGreenTable
PingPongGameEngine
GameConstants.
,
,
,
GameConstants.
PingPongGreenTable
GameConstants.
package screens;
import
import
import
import
import
import
import
import
import
import
import
javax.swing.JPanel;
javax.swing.JFrame;
javax.swing.BoxLayout;
javax.swing.JLabel;
javax.swing.WindowConstants;
java.awt.Point;
java.awt.Dimension;
java.awt.Container;
java.awt.Graphics;
java.awt.Color;
engine.PingPongGameEngine;
/**
-
,
*/
publicclass PingPongGreenTable extends JPanel
implements GameConstants{
JLabel label;
public Point point = new Point(0,0);
Java , ,
197
Java , ,
198
//
g.fillRect(ComputerRacket_X,100,5,30);
g.setColor(Color.red);
g.fillOval(25,110,10,10); //
g.setColor(Color.white);
g.drawRect(10,10,300,200);
g.drawLine(160,10,160,210);
// 2x2
if (point != null) {
label.setText("Coordinates (x,y): " + point.x +
", " + point.y);
g.fillRect(point.x, point.y, 2, 2);
}
}
//
public void setKidRacket_Y(int xCoordinate){
this.kidRacket_Y = xCoordinate;
}
//
public int getKidRacket_Y(int xCoordinate){
return kidRacket_Y;
}
publicstaticvoid main(String[] args) {
//
JFrame f = new JFrame("Ping Pong Green Table");
// ,
//
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
PingPongGreenTable table = new PingPongGreenTable();
table.addPaneltoFrame(f.getContentPane());
//
f.pack();
f.setVisible(true);
}
Java , ,
199
GameConstants.
.
final
:
package screens;
public interface GameConstants {
public
public
public
public
public
public
public
final
final
final
final
final
final
final
int
int
int
int
int
int
int
TABLE_WIDTH = 320;
TABLE_HEIGHT = 220;
KID_RACKET_Y_START = 100;
KID_RACKET_X_START = 300;
TABLE_TOP = 12;
TABLE_BOTTOM = 180;
RACKET_INCREMENT = 4;
,
final.
,
,
,
,
TABLE_WIDTH
TABLE_HEIGHT
GameConstants.
PingPongGameEngine,
2
,
.
MouseListener
mousePressed().
.
,
,
MouseEvent
,
JVM.
mousePressed()
point.
,
,
.
MouseMotionListener
,
mouseMoved()
.
mouseMoved()
.
(
Y
,
Y
),
,
.
PingPongGreenTable
PingPongGameEngine,
(
this
PingPongGreenTable).
,
PingPongGameEngine
,
,
Java , ,
200
,
.
,
6
.
4
,
GameConstants
(
PingPongGameEngine
).
,
4
kidRacket_Y:
kidRacket_Y -= RACKET_INCREMENT;
,
Y
100,
96
.
:
kidRacket_Y = kidRacket_Y - RACKET_INCREMENT;
,
3.
PingPongGameEngine.
package engine;
import
import
import
import
java.awt.event.MouseEvent;
java.awt.event.MouseListener;
java.awt.event.MouseMotionListener;
screens.*;
Java , ,
201
// paintComponent()
table.repaint();
}
public
public
public
public
void
void
void
void
mouseReleased(MouseEvent e) {};
mouseEntered(MouseEvent e) {};
mouseExited(MouseEvent e) {};
mouseClicked(MouseEvent e) {};
// MouseMotionListener
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
int mouse_Y = e.getY();
//
//
// ,
if (mouse_Y < kidRacket_Y && kidRacket_Y > TABLE_TOP){
kidRacket_Y -= RACKET_INCREMENT;
}else if (kidRacket_Y < TABLE_BOTTOM) {
kidRacket_Y += RACKET_INCREMENT;
}
//
table.setKidRacket_Y(kidRacket_Y);
table.repaint();
}
}
.
,
,
.
,
(a
thread).
,
,
,
,
,
.
Java , ,
202
,
:
,
.
,
o
(CPU).
,
,
,
,
,
,
..
,
(multiple
threads).
Java-
,
.
,
web-.
-,
.
-
.
,
.
,
,
,
.
Java , ,
203
Kill
Time,
,
.
.
NoThreadsSample
,
.
,
.
,
,
.
,
JTextField
.
,
.
import
import
import
import
javax.swing.*;
java.awt.GridLayout;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
this.getContentPane().add(myButton);
this.getContentPane().add(new JTextField());
//
public void actionPerformed(ActionEvent e){
// ,
// ,
for (int i=0; i<300000;i++){
this.setTitle("i="+i);
Java , ,
204
}
}
public static void main(String[] args) {
//
NoThreadsSample myWindow = new NoThreadsSample();
// ,
myWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//
//
myWindow.setBounds(0,0,150, 100);
//
myWindow.setVisible(true);
}
,
,
.
:
Java-
Thread
,
Runnable.
Runnable,
:
Thread worker = new Thread(this);
run()
,
.
worker.start();
Thread
run().
,
,
start().
public class MyThread extends Thread{
Java , ,
205
//
}
ThreadsSample
,
JFrame,
Java
.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ThreadsSample extends JFrame
implements ActionListener, Runnable{
//
ThreadsSample(){
//
GridLayout gl =new GridLayout(2,1);
this.getContentPane().setLayout(gl);
JButton myButton = new JButton("Kill Time");
myButton.addActionListener(this);
this.getContentPane().add(myButton);
this.getContentPane().add(new JTextField());
Java , ,
206
,
-.
PingPongGreenTable.
.
point
,
paintComponent().
,
MouseListener,
.
,
(N
,
S
Q
).
addKeyListener().
,
,
repaint()
PingPongGameEngine
PingPongGreenTable.
,
,
PingPongGreenTable
.
Java , ,
207
,
,
.
package screens;
import
import
import
import
import
import
import
import
import
import
javax.swing.JPanel;
javax.swing.JFrame;
javax.swing.BoxLayout;
javax.swing.JLabel;
javax.swing.WindowConstants;
java.awt.Dimension;
java.awt.Container;
java.awt.Graphics;
java.awt.Color;
engine.PingPongGameEngine;
/**
* -,
, ,
*/
public class PingPongGreenTable extends JPanel
implements GameConstants{
private
private
private
private
private
JLabel label;
int computerRacket_Y = COMPUTER_RACKET_Y_START;
int kidRacket_Y = KID_RACKET_Y_START;
int ballX = BALL_START_X;
int ballY = BALL_START_Y;
Java , ,
208
container.setLayout(new BoxLayout(container,BoxLayout.Y_AXIS));
container.add(this);
label = new JLabel(
"Press N for a new game, S to serve or Q to quit");
container.add(label);
}
// .
// ,
// repaint() PingPointGameEngine
public void paintComponent(Graphics g) {
super.paintComponent(g);
//
g.setColor(Color.GREEN);
g.fillRect(0,0,TABLE_WIDTH,TABLE_HEIGHT);
//
g.setColor(Color.yellow);
g.fillRect(KID_RACKET_X, kidRacket_Y,
RACKET_WIDTH, RACKET_LENGTH);
//
g.setColor(Color.blue);
g.fillRect(COMPUTER_RACKET_X, computerRacket_Y,
RACKET_WIDTH,RACKET_LENGTH);
//
g.setColor(Color.red);
g.fillOval(ballX,ballY,10,10);
//
g.setColor(Color.white);
g.drawRect(10,10,300,200);
g.drawLine(160,10,160,210);
// ,
//
requestFocus();
}
//
public void setKidRacket_Y(int yCoordinate){
this.kidRacket_Y = yCoordinate;
repaint();
}
//
public int getKidRacket_Y(){
Java , ,
209
return kidRacket_Y;
}
//
public void setComputerRacket_Y(int yCoordinate){
this.computerRacket_Y = yCoordinate;
repaint();
//
public void setMessageText(String text){
label.setText(text);
repaint();
}
//
public void setBallPosition(int xPos, int yPos){
ballX=xPos;
ballY=yPos;
repaint();
final
GameConstants,
,
.
package screens;
/**
* ,
*/
public interface GameConstants {
//
public final int TABLE_WIDTH =
320;
Java , ,
210
1+ BALL_INCREMENT;
1 + BALL_INCREMENT;
TABLE_WIDTH - BALL_INCREMENT;
TABLE_HEIGHT - BALL_INCREMENT;
//
public final int BALL_START_X = TABLE_WIDTH/2;
public final int BALL_START_Y = TABLE_HEIGHT/2;
//,
public
public
public
public
public
public
public
public
final
final
final
final
final
final
final
final
int
int
int
int
int
int
int
int
KID_RACKET_X = 300;
KID_RACKET_Y_START = 100;
COMPUTER_RACKET_X = 15;
COMPUTER_RACKET_Y_START = 100;
RACKET_INCREMENT = 2;
RACKET_LENGTH = 30;
RACKET_WIDTH = 5;
WINNING_SCORE = 21;
// ,
//
public final int SLEEP_TIME = 10; //
,
PingPongGameEngine:
MouseListener
,
.
MouseMotionListener.
Runnable,
run().
.
run()
,
if(ballServed).
if(ballServed==true).
,
,
canBounce
.
,
true,
false.
Java , ,
211
KeyListener,
keyPressed()
,
/
,
.
,
,
N
n.
private
:
displayScore(),
kidServe()
isBallOnTheTable().
,
.
.|
,
.
Thread.sleep().
sleep()
.
,
.
X
,
Y.
package engine;
import
import
import
import
import
java.awt.event.MouseMotionListener;
java.awt.event.MouseEvent;
java.awt.event.KeyListener;
java.awt.event.KeyEvent;
screens.*;
/**
* .
* , .
*/
public class PingPongGameEngine implementsRunnable,
MouseMotionListener, KeyListener, GameConstants{
private
private
private
private
private
private
private
private
private
PingPongGreenTable table; //
int kidRacket_Y = KID_RACKET_Y_START;
int computerRacket_Y=COMPUTER_RACKET_Y_START;
int kidScore;
int computerScore
int ballX;
// X
int ballY;
// Y
boolean movingLeft = true;
boolean ballServed = false;
Java , ,
212
//
private int verticalSlide;
// .
public PingPongGameEngine(PingPongGreenTable greenTable){
table = greenTable;
Thread worker = new Thread(this);
worker.start();
}
// MouseMotionListener
// ( , )
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
int mouse_Y = e.getY();
//
// ,
//
if (mouse_Y<kidRacket_Y && kidRacket_Y>TABLE_TOP){
kidRacket_Y -= RACKET_INCREMENT;
}elseif (kidRacket_Y < TABLE_BOTTOM) {
kidRacket_Y += RACKET_INCREMENT;
}
//
table.setKidRacket_Y(kidRacket_Y);
}
// KeyListener
public void keyPressed(KeyEvent e){
char key = e.getKeyChar();
if ('n' == key || 'N' == key){
startNewGame();
} elseif ('q' == key || 'Q' == key){
endGame();
} elseif ('s' == key || 'S' == key){
kidServe();
}
Java , ,
213
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
//
public void startNewGame(){
computerScore=0;
kidScore=0;
table.setMessageText("Score Computer: 0
}
Kid: 0");
kidServe();
//
public void endGame(){
System.exit(0);
}
// run() Runnable
public void run(){
boolean canBounce=false;
while (true) {
if(ballServed){ //
// 1. ?
if ( movingLeft && ballX > BALL_MIN_X){
canBounce = (ballY >= computerRacket_Y &&
ballY < (computerRacket_Y + RACKET_LENGTH)?true: false);
ballX-=BALL_INCREMENT;
//
//
ballY-=verticalSlide;
table.setBallPosition(ballX,ballY);
// ?
if (ballX <= COMPUTER_RACKET_X
&& canBounce){
movingLeft=false;
}
}
// 2. ?
if ( !movingLeft && ballX <= BALL_MAX_X){
canBounce = (ballY >= kidRacket_Y && ballY <
Java , ,
214
(kidRacket_Y + RACKET_LENGTH)?true:false);
ballX+=BALL_INCREMENT;
table.setBallPosition(ballX,ballY);
// ?
if (ballX >= KID_RACKET_X && canBounce){
movingLeft=true;
}
// 3. ,
//
if (computerRacket_Y < ballY
&& computerRacket_Y < TABLE_BOTTOM){
computerRacket_Y +=RACKET_INCREMENT;
}else if (computerRacket_Y > TABLE_TOP){
computerRacket_Y -=RACKET_INCREMENT;
}
table.setComputerRacket_Y(computerRacket_Y);
// 4.
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 5. , ,
if (isBallOnTheTable()){
if (ballX > BALL_MAX_X ){
computerScore++;
displayScore();
}else if (ballX < BALL_MIN_X){
kidScore++;
displayScore();
}
} // if ballServed
} // while
}// run()
Java , ,
215
//
private void kidServe(){
ballServed = true;
ballX = KID_RACKET_X-1;
ballY=kidRacket_Y;
if (ballY > TABLE_HEIGHT/2){
verticalSlide=-1;
}else{
}
verticalSlide=1;
table.setBallPosition(ballX,ballY);
table.setKidRacket_Y(kidRacket_Y);
private void displayScore(){
ballServed = false;
if (computerScore ==WINNING_SCORE){
table.setMessageText("Computer won! " + computerScore +
":" + kidScore);
}else if (kidScore ==WINNING_SCORE){
table.setMessageText("You won! "+ kidScore +
":" + computerScore);
}else{
table.setMessageText("Computer: "+ computerScore +
" Kid: " + kidScore);
}
// ,
private boolean isBallOnTheTable(){
if (ballY >= BALL_MIN_Y && ballY <= BALL_MAX_Y){
return true;
}else {
return false;
}
}
}
Java , ,
216
!
.
.
,
,
,
,
.
, Robocode
,
Java,
:
http://robocode.sourceforge.net/?Open&ca=daw-prod-robocode
Java:
http://www.oracle.com/technetwork/java/socket-
140484.html
Java:
http://www-106.ibm.com/developerworks/edu/j-dw-
javathread-i.html
java.awt.Graphics:
http://download.oracle.com/javase/6/docs/api/java/awt/G
raphics.html
Java , ,
217
1.
PingPongGameEngine
:
table.point.x = e.getX();
point
PingPongGreenTable
public
setPointCoordinates(int
x, int y).
PingPongGameEngine.
2.
-
:
,
,
S
.
.
1.
RACKET_INCREMENT
BALL_INCREMENT.
,
.
,
1
10.
.
2.
,
.
,
,
.
Java , ,
218
A. Java - JARs
.
USB
flash
drive,
CD,
.
,
-
.
,
,
.
Java
jar,
Java
.jar.
jar
,
WinZip
(
2-
)
.
,
jar.
1.
,
jar
.class,
,
,
:
jar cvf myClasses.jar *.class
Java , ,
219
jar
.
,
v
,
f
,
.
.
,
myClasses.jar,
:
jar xvf myClasses.jar
.
x
.
jar-
,
,
t
.
jar tvf myClasses.jar
,
WinZip
,
,
jar-.
Java
,
jar-.
,
jar,
,
.
Jar java-:
http://download.oracle.com/javase/7/docs/technotes/tools
/windows/jar.html
Java , ,
220
.
Eclipse
Eclipse ,
Java
.
Eclipse,
,
,
.
,
.
F3.
,
.
,
,
.
Ctrl-F11,
.
,
Eclipse
.
,
,
Ctrl-.
,
Ctrl-V.
Java , ,
,
,
,
Refactor
Rename
.
Eclipse
,
.
jar-
(,
-
),
,
Properties,
Java
Build
Path
Add
External
Jars.
221
Eclipse
,
50
,
,
,
.
(.
bug),
-
.
,
.
,
(.
debug)
.
.
,
,
2,
22.
,
.
,
.
Java , ,
222
,
Eclipse
FishMaster
.
(breakpoint)
,
,
,
/
,
.
,
,
,
.
FishMaster,
myFish.dive(2).
.
,
Run,
Debug....
FishMaster
Debug.
FishMaster
myFish.dive(2),
.
,
:
Java , ,
223
,
.
,
.
Variables,
myFish.
..
Fish,
,
,
currentDepth=20.
.
.
(
F5),
dive().
,
howDeep=2,
.
this
,
.
,
,
.
,
,
.
-
,
-
.
Java , ,
224
,
,
(
F6).
,
F8.
,
,
,
.
,
,
.
?
,
,
.
,
,
main()
,
.
Java , ,
225
.
-
- HTML (
JavaScript),
,
..
HTML
7,
-,
HTML.
:
www.w3schools.com.
,
-
,
-
,
,
.
HTML,
.
,
,
-
Java
(
!)
HTML
.
,
-,
,
HTML
,
,
.
,
,
()
,
.
-.
-,
-
.
,
,
HTML
.
:
Java , ,
226
(
).
,
.
-
(URL)
,
.
,
,
.
100
,
.
,
.
,
.
FTP-.
FTP-
FTP
Explorer,
www.ftpx.com.
-
FTP-
FTP
Explorer
,
,
.
,
Connection
Tools
(
).
Java , ,
227
Add
,
,
-.
Profile
Name
.
,
FTP-.
Connect
.
,
.
.
,
.
,
HTML
.
,
Open.
.
Java , ,
228
,
.
index.html.
URL
,
.
,
www.xyz.com/~David
myMainPage.html,
www.xyz.com/~David/myMainPage.html.
,
index.html,
www.xyz.com/~David.
,
,
.
,
,
,
.
,
.
-,
,
JavaScript.
,
Java
-
.
,
HTML
,
.
(http://narod.yandex.ru/)
.
.
Java , ,
229
-
-
7.
,
,
TicTacToe.html
TicTacToe.class.
,
,
.
-
,
?
Java
Tutorial.
24-Hour
Trainer.
DVD,
.
-
.
.
URL
:
http://www.amazon.com/Java-Programming-24-Hour-Trainer-
Yakov/dp/04708896402
-!
Java , ,
230
!, 63
&&, 63
||, 62
Access
Levels, 176
ActionListener, 100
actionPerformed, 100
Adapters, 114
algorithm, 124
argument, 38
array, 69, 70, 71
ArrayList, 186, 187, 188
arrays, 183
AWT, 76
BorderLayout, 84, 125
BoxLayout, 88
break, 66, 72
Buffered Streams, 155
BufferedInputStream, 155
BufferedOutputStream, 157
callback
methods, 121
CardLayout, 90
Casting, 102
catch, 142, 144
checked
exceptions, 140
CLASSPATH, 18, 20
conditional
if, 63
constructor, 67, 68
continue, 72, 73
date, 169
Debug, 222
do while, 73
Download Eclipse, 23
Eclipse, 23
else if, 64
encapsulation, 182, 183
events, 79
Exception, 140, 143
exceptions, 137
extends, 52, 55
File, 164
FileInputStream, 153
FileOutputStream, 154
FileReader, 160
FileWriter, 160
finally, 145, 146
FlowLayout, 82
frame, 78
FTP, 227
GridBagConstraints, 89
GridBagLayout, 89
GridLayout, 82
HelloWorld, 36
HTML, 116, 117, 119, 122
I/O, 138
IDE, 23
implement, 98
implements, 98
import, 77
instance, 105
instance
variables, 67
instanceof, 104
interfaces, 97
jar, 218
javadoc, 59
JDK, 14
JRE, 21, 30
JVM, 13
Layout manager, 78
listeners, 101
Logical Operators, 62
Loops, 71
member
variable, 67
method
overloading, 171
method signature, 36
new, 67
Object, 54
override, 56
packages, 176, 178
panel, 78
Java , ,
PATH, 20
private, 179, 180, 189
Program
Arguments, 159
protected, 179, 182
public, 36, 179
run-time errors, 137
scope, 67
showConfirmDialog, 100
stack
trace, 138
static, 36, 67
streams, 152
Swing, 76, 93
switch, 65
system
variables, 17
this, 68
thread, 201, 204
throw, 147
throws, 144
TicTacToe, 117
time, 169
try, 141, 144, 146
try/catch, 141
void, 36, 49
WindowsListener, 114
, 120
, 47
, 40
, 225
, 98
, 19
, 46
, 40
-, 114
, 59
231
, 44
, 173
, 63
, 62
, 63
, 48
, 40
, 52
, 43
if, 60
, 221
, 48
, 43
, 56
, 125
, 97
,
112
, 112
, 112
, 112
, 112
, 112
, 97
-, 52
, 81
, 42
while, 72
for, 71
, 160
, 105
, 43