SL-275
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
吉大教育
Java 语言与基本类库讲义大纲
第1章基本概念(3)
1.1 H ello world程序
public class A {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
}
}
1.2 JDK与JRE
1.2.1 Java开发包(JDK: Java Development Kit)
(1) 编译器javac.exe
(2) 归档软件jar.exe
(3) 文档生成器javadoc.exe
(4) 生成C头文件软件javah.exe
1.2.2 Java运行时环境(JRE: Java Runtime Environment)
(1) Java虚拟机(JVM: Java Virtual Machine)
(2) 运行时包
(3) 环境变量
●Jdk_home
●Path=%path%;%jdk_home%\bin
1.3 包与类路径
1.3.1 包(package)
(1) 概念
包是子目录,是为了管理类文件(.class文件)提出的。
(2) 源文件中加包
package math.a;
吉大教育
public class A {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
}
}
编辑后,要重新编译,生成类文件。
(3) 建包
在指定的路径下,建立math\a子目录。
把类文件拷入这个目录下。
包
(4) 运行包中类
java –classpath d:\yang\ex1108\bin; math.a.A
1.3.2 类路径(class path)
(1) 设置
(2) JVM参数
●-classpath或-cp
●-verbose
1.3.3 打包
jar: java archive
war: web archive
(1) 打包工具:jar
用法: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] file
s ...
选项包括:
-c 创建新的归档文件
-t 列出归档目录
-x 解压缩已归档的指定(或所有)文件
-u 更新现有的归档文件
-v 在标准输出中生成详细输出
-f 指定归档文件名
-m 包含指定清单文件中的清单信息
-e 为捆绑到可执行jar 文件的独立应用程序
指定应用程序入口点
-0 仅存储;不使用任何ZIP 压缩
-M 不创建条目的清单文件
-i 为指定的jar 文件生成索引信息
-C 更改为指定的目录并包含其中的文件
如果有任何目录文件,则对其进行递归处理。
清单文件名、归档文件名和入口点名的指定顺序
与"m"、"f" 和"e" 标志的指定顺序相同。
示例1:将两个类文件归档到一个名为classes.jar 的归档文件中:jar cvf classes.jar Foo.class Bar.class
示例2:使用现有的清单文件"mymanifest" 并
将foo/ 目录中的所有文件归档到"classes.jar" 中:jar cvfm classes.jar mymanifest -C foo/ .
(2) 清单文件:a.mf
Manifest-Version: 1.0
Created-By: 1.6.0_01 (Sun Microsystems Inc.)
Main-Class: com.jida.date.MyDate
(3) 打包
D:\yang\ex1108\bin>jar cvfm a.jar d:\yang\ex1108\a.mf .
(4) 运行
方式1:D:\yang\ex1108\bin>java –jar a.jar
方式2:D:\yang\ex1108\bin> java –cp a.jar; com.jida.data.MyDate 1.4 Eclipse集成开发环境
(1)新建工程(Project)
(2)设置: JA V A
(3)工程属性(Project Properties)
习题
习题1.1 设计指定包下的程序并编译、运行
习题1.2 Eclipse 中JDK设置
习题1.3 打包
第2章Java 语言
2.1 基本数据类型(Primitive Type)(1.5)
(1) 类型(type)
程序设计为什么必须使用类型?
内存定义:内存大小和解释方式
(2) 基本类型(Primitive type)
类型描述内存大
小
范围实例常量
byte 字节 1 -27—27-1 byte b; (byte)100
cast
(i )变量声明的作用:内存分配
int nDoorHeight; nDoorHeight=2000;
nDoorHeight=nDoorHeight+100;
byte b;
(ii )数的范围 C 中 char c;
unsigned char c; signed char c; 在Java 中不用。
int: integer |-231|=-231
(iii )进制:
0111 1111 1111 1111
215-1 ……
0000 0000 0000 0001
1 0000 0000 0000 0000
0 1111 1111 1111 1111
-1 ……
1000 0000 0000 0000
-215
01111 1111 127 …… 0000 0010 2 0000 0001 1 0000 0000 0 1111 1111 -1 1111 1110 -2 1111 1101 …… 1000 0000 -128
吉大教育
103=0.102*103;
(iv) 编码
●ASCII
0-32
8 退格
9 制表
10 换行
13 回车
32 空格
48 ‘0’
65 ‘A’
97 ‘a’
Char c=’9’;
System.out.println(c-‘0’);
●GBK
●GB2312
●Unicode
<a href=”index.html”>
返回首页
</a>
“c:\tt\tt.txt”
2.2 操作符(Operator)(1.5)
2.2.1 算术操作符(Arithmetic Operator)
例:
今天是星期6,18天之后星期几?设今天是星期1, 18天之前星期几?
System.out.println((18%7+6)%7);
System.out.println((7-18%7+1)%7);
System.out.println(-6%-4);
2.2.2 关系操作符(Relation Operator)
2.2.3 逻辑操作符(Logical Operator)
各逻辑操作符的定义见表1.6。
表2。
2。
3 逻辑操作符定义
其中“&&”与“||”是短路操作符,即若“&&”的第一操作数为假时,第二个操作数不再被求值;若“||”的第一操作数为真时,第二个操作数不再被求值;
例2.1 给定年y, 计算y是否是闰年.
2.2.4 ?: 操作符
E?E1:E2
例2.2 给定年y, 计算y的天数.
public class MyDate {
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int y=1900;
System.out.println(y+":"+isLeap(y)+","+getDays(y));
y=2000;
System.out.println(y+":"+isLeap(y)+","+getDays(y));
y=1996;
System.out.println(y+":"+isLeap(y)+","+getDays(y));
y=1997;
System.out.println(y+":"+isLeap(y)+","+getDays(y));
}
public static boolean isLeap(int y){
return y%4==0 && y%100!=0 || y%400==0;
}
public static int getDays(int y){
return isLeap(y)?366:365;
}
}
2.2.5 位操作符(Bitwise Operator)
6^3
00000000..00 0110 00000000..00 0011 00000000..00 0010 ~6: 0xff ff ff ff f9 -6 =~6+1
2.2.6 位移操作符(Shift Operator)
例:
int x=1;
x=x<<31;//-2^31
System.out .println(x>>31);
System.out .println(x>>>31); 例:
int x=0x44444444;
System.out .println((x&0xf8)>>3);
2.3 语句(5)
2.3.1 赋值语句(Assignment Statement)
(1) 一般文法 左值=Expression; int x;
x=1;
x=x+5;
左值:可内存寻址的量或表达式。
f()[4]=6; x=y=6;//y=6 (2) 简写形式
x+=5; x=x+5;
w%=7; w=w%7;
赋值表达式: if((x=y+5)>0){
} 例:x=y=8;
4=x;
(4) 自加
(减)
x=x+1; x+=1; x++;
int y;
x=5;
y=x++;// x++
是5, 后x 加1,将5送给y. System.out .println("x="+x+" y="+y); x=5;
y=++x; // ++x 是6,将6送给y.
System.out .println("x="+x+" y="+y);
2.3.2 条件语句
if(E)
S if(E) S1 else S2
例:
x=3;
y=4; if (x>y)
x++;
y--;
System.out .println(x+","+y);
x=3;
y=4; if (x>y) x++; y--;
else
x--;
y++;
System.out .println(x+","+y);
x=2;
int a=2,b=3,c=4; if (a>b)
if (b>c) x=3; else if (a<b) x=4; else if (b<c) x=5;
else x=6;
System.out .println(x);
吉大教育
2.3.3 复合语句
{
}
2.3.4 循环语句
(1) while
while(E)
S
(2) for
for(S0; E; S1)
(3) do-while do
S while(E);
例2.3 计算1+2+3+…+m
例2.4 打印m*n矩阵
给定行数n=7
*
* *
* *
* *
* *
* *
*
do
S
while(E);
public static void doWhileTest(){
int x=5,y=9;
do
while(x<9)//b1
System.out.println(x++);
while(x<=y);//b2
}
2.3.5 break语句
吉大教育
(1) break;
(2) break label;
2.3.6 continue语句
继续循环:跳到循环控制处继续。
只用在循环中。
(1) continue;
(2) continue label;
例:1+2+4+5+7+8+…
2.3.7 空语句
;
2.3.8 switch语句--开关语句
例2.5 给定y年m月, 计算其天数.
public static int getDays(int y,int m ){
switch(m){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return isLeap(y)?29:28;
default:
return 0;
}
}
例:
public static void switchTest(){
char c='A';
int k=1;
吉大教育
case'A': k++;break;
case'B': k*=3; continue;
case'C': k--;
default: k%=4;
case'D': k+=3;
}
k++;
}
while(c<'F');
}
2.3.9 return语句
return ; 当函数返回类型是void
return E ; 当函数返回类型是非void
函数调用
public static void main(String[] args) {
// TODO Auto-generated method stub
f1(5);
}
public static void f1(int x){
int i=2;
int j=5;
f2(i,j);
}
public static int f2(int x,int y){
f3();
return 0;
}
public static void f3(){
int x,y;
x=y=6;
System.out.println(x+","+y);
}
main
50 80
100
Return:
S1 释放局部变量空间
S2 灰复现场
例:f(m)=1+2+3+4+…+m-1+m
f(m)=f(m-1)+m
=0 m<=0
5 f(6);
10 public static int f(int m){
11 if(m<=0)
12 return 0;
13 return f(m-1)+m;//f(m-1) f(m-1)+m return
14
15 }
Main 5
F:11
F:13:1
F:11
F:13:1
F:11
F:13:1
F:11
F:13:1
F:11
F:13:1
F:11
F:12
F:13:2
F:13:3
F:13:2
2.3.10 方法调用
例2.6 万年历程序
已知年y, 打印y 年的日历。
(参照2000年1月1 日星期6)解:
S1 求y 年第一天星期几
S11 求y年1 月1 日距2000年1月1 日的天数
S12 求y 年第一天星期几
S2 求y 年m月第一天星期
S3 打印y年日历
要求:代码要在15分钟内完成。
例2.7 冒泡排序
例2.8 快排序
例2.9 堆排序
习题
习题2.1 例2.11在15分钟内完成
习题2.2 实现各种内部排序程序
习题2.3 打印n×m个菱形,并绘出流程图
习题2.3 递归程序训练
第3章 面向对象程序设计
3.4 面向对象与类(3)
3.4.1 面向对象程序设计(Object Oriented Programming)
(1) 对象(Object ) :客观实体 关系 事件 (2) 面向对象(Object Orient ): 属性:数据
行为:函数 (3)OOP :
UML: Class diagram
类是对象的加工厂 实例:内存块
例2.7 平面上的点的类 把下面的4个点表示到计算机内
(5,10) (10,10)
(5,5) (10,5)
Rational Rose
S1. 分析出类
S2. 用Java描述出来
S3. 建立实例
例2.8 Human、Dog、Mammal、Eye类之间的关系
3.4.2 类文法
public class Person extends Object {
public void display() {
}
}
Object是所有类父类,ng.Object
类间关系: is-a has-a
例:
Doctor is a person. Person is a mammal. Dos is a mammal too. Person had two eyes and dog two eyes too.
Super class :超类
Sub class:子类
Public class Class{
}
3.4.3 public 修饰符
(1)java文件中至多只能有一个public类,public类名与文件名同。
3.4.4 final和abstract修饰符
Final:最后
The type MyString cannot subclass the final class String.
String是final 类。
abstract:抽象,抽象类是半实现的类。
Cannot instantiate the abstract class
3.4.5 引用(reference)和实例(instance)
Point p1=new Point();
Point p1=new Point();
p1:引用,reference,例:com.jida.chess.Point@de6ced new Point():实例化,执行4 步
S2 隐式初始化
S3 显示初始化
S4 执行构造器
3.5 方法(3)
3.5.1 定义文法(syntax)
Public
Protected
(package)
Private
Special modifier:
Static
Final
Abstract
Return type:
Void
Primitive type
Class
空
3.5.2 final 和abstract修饰
Final:
class A1{
final void f(){
}
void ff(){
}
}
class A2 extends A1{
void f(){ //f here overrides f in A1 重写 cannot overrides final method
}
void ff(){
}
}
注意:
abstract: 抽象方法是未实现的方法。
实质是协议,它规定了派生类必须完成行为。
3.5.3 static修饰
1.不依赖于实例
public class StaticTest {
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main beginning");
// C1.f();
C1.f1();
C1 c1=new C1();//instance
c1.f();
c1.f1();
}
}
class C1{
void f(){//non-static
}
static void f1(){//static
}
}
2.在装入类时就有定义、使用
3.实质上是“全程”方法
4.Math类
5.包裹类(Wrapper Class)
a)Byte
b)Short
c)Integer
d)Long
e)Float
f)Double
g)Character
h)Boolean
6. 自动柝箱、装箱
int x=5;
Integer i=x+2;//new Integer(7);
吉大教育i++;
byte和Byte
short和Short
3.5.4 构造器(Constructor)
(1) 基本要求
●名与类名同
●无返回类型
●创建实例时,自动被调用
(2) 构造顺序:先构造超类,后构造子类
package com.jida.chess;
public class Point {
private int x;
private int y;
// public Point(){
//
// }
public Point(int x,int y){//constructor
this.x=x;
this.y=y;
}
// public void Point(){//not constructor
//
// }
/**
*@param args
*/
public static void main(String[] args) {
吉大教育
// TODO Auto-generated method stub
Point p1=new Point(5,5);
// p1.x=5
// p1.y=5;
p1.display();
Point p2=new Point(10,10);
// p2.x=10;
// p2.y=10;
p2.display();
Point t=p1;
p1=p2;
p2=t;
p1.display();
p2.display();
}
public String toString(){
return"("+x+","+y+")";
}
public void display(){
System.out.println(toString());
}
public int getX() {//getter
return x;
}
public void setX(int x) {//setter
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
package com.jida.chess;
public class ChessPoint extends Point {
private int state; //1: black; 2: white; 0: none
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ChessPoint cp=new ChessPoint();
吉大教育
}
public String toString(){
return super.toString()+":"+state;
}
public void display(){
System.out.print(toString());
}
}
(3) super()和this()
super(): 调用超类的构造
this(): 调用当类的其它构造
*任何类的构造器第一行代码都是super()调用。
若无,则编译器自动加。
(4) 公共代码
{//公共代码common
}
Super()→commom→this()
所有构造器中公共的代码
(5) 静态初始化器(static initializer)
static{
System.out.println("static");
}
2.6 变量(1)
2.6.1 文法(syntax)
public static final int BLACK=1;
public static final int WHITE=2;
public static final int NONE=3;
public static final int WORDLENGTH=145;
吉大教育2.6.2 final修饰字
可修饰局部变量和成员变量。
Final field cannot be assigned.
类常量
实例常量
局部常量
public class FinalTest {
public static final int LEN=20;//类常量
private final int bloodPressure;//实例常量
public FinalTest(int bloodPressure){
this.bloodPressure=bloodPressure;
// this.bloodPressure +=2;
}
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void f(){
final A2 a=new A2();//局部常量,在堆中,只在本函数中使用
// a=6;
// a=new A2();
a.x=5;
a.x=6;
}
}
class A2{
int x;
}
2.6.3 static修饰字
不依赖于实例。
在类装入时在堆中分配内存。
public class FinalVarTest {
public static final int LEN=145; //类常量
public final int HEI; //实例常量
public FinalVarTest(int hei){
吉大教育
HEI =hei;
}
public static void main(String[] args) {
final int i=7;//不在栈中 · new FinalVarTest(50); new FinalVarTest(60); }
}
例:所有雇员共用一个帐号。
public class Employee { private Account acc ; private String name ;
public Employee(String name,Account acc){ this .name =name; this .acc =acc;
}
public static void main(String[] args) { // TODO Auto-generated method stub Account acc=new Account();
Employee li=new Employee("li" ,acc); Employee liu=new Employee("liu" ,acc); Employee liang=new Employee("liang" ,acc); }
}
class Account{ private float balance ;
public void withdraw(float x){
this .balance -=x;
FinalVarTest
HEI Object FinalVarTest.LEN
FinalVarTest HEI
Object
}
public void deposit(float x){ this .balance +=x;
}
}
2.6.4 初始化(Initialization)
(i) 成员变量: 自动初始化 (ii) 局部变量: 手动初始化
2.7 访问控制修饰符(1)
例2.10 单例设计模式,设计一个类,只能创建一个实例。
注:这是一个设计模式。
代码如下:
public class Singlton {
private static Singlton inst=new Singlton();
private Singlton(){
}
public static Singlton getInstance(){
return inst;
}
}
2.8 数组(2)
2.8.1 一维
(1) 文法
public static void test1(){
吉大教育
//一维数组
int a[]; //定义数组引用a a=new int [10]; a=new int [0]; a=new int [1]; a=new int []{5,3,1};
}
(2) 内存分配示意图
(3) 基本概念 数组对象 a
数组实例 new int [10] 数组元素 a[i]
数组长度 元素个数 a.length
数组索引 a[i] i 是索引,也称为下标
数组下标超界异常 ArrayIndexOutoutBoundException (4) 遍历
Point [] points;
(1) 文法
吉大教育aa=new int[2][3];
aa[0]=new int[5];
aa=new int[][]{{1,2},{3},{4,5,6}};
(2) 内存分配示意图
(3) 遍历
例2.11 五子棋棋盘的描述
2.9 Super和this
例1:
例2:
例3:
public class ThisTest {
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
/**
*@param args
吉大教育
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThisTest tt=new ThisTest();
tt.getSelf();
ThisTest tt1=new ThisTest();
tt1.getSelf();
int x=6;
tt1.setX(x);
Table t=new Table();
Chair ch=new Chair();
t.ch=ch;
ch.t=t;
Table1 t1=new Table1();
Chair1 ch1=new Chair1(t1);
new Table2();
}
public ThisTest getSelf(){
return this;
}
}
class Table{
Chair ch;
}
class Chair{
Table t;
}
class Table1{
Chair1 ch;
public void addChair1(Chair1 ch){
this.ch=ch;
}
}
class Chair1{
Table1 t;
public Chair1(Table1 t){
this.t=t;
t.addChair1(this);
}
}
class Table2{
Chair2 ch;
public Table2(){
ch=new Chair2(this);
}
}
class Chair2{
Table2 t;
public Chair2(Table2 t){
this.t=t;
// t.addChair1(this);
}
}
1 2 3 4 5 6 7 8 9.54
壹贰叁肆伍陆柒捌玖
仟佰拾仟佰拾
亿万圆
2.10 重载与覆盖(2)
多态(Polymorphism)
(1)基于类解析不同的调用
(2)同一类,参数不同,由compiler基于参数解析不同的调用(Overload)
(3)基于person所引用对象的不同,解析调用,compiler无法确定,迟后联编(编辑时--运行时),运行时处理需要额外(内存)开销。
(Override)
2.10.1 重载(Overload)
例2.12 命令设计模式
abstract public class Command {
abstract public void execute();
public static void main(String s[]){
Person11 li=new Person11("li",new CommandCook());
Person11 liu=new Person11("liu",new CommandClean());
Person11 lin=new Person11("lin",new CommandProgram());
li.work();
liu.work();
lin.work();
}
}
class CommandClean extends Command{
public void execute(){
System.out.println("Cleaning");
}
}
class CommandCook extends Command{
public void execute(){
System.out.println("Cooking");
}
}
class CommandProgram extends Command{
public void execute(){
System.out.println("programming");
}
}
class Person11{
private Command com;
private String name;
Person11(String name,Command com){
=name;
=com;
}
public void work(){
System.out.println(name);
com.execute();
}
}
2.11 异常(2)
2.11.1 概念
M1 上传(propagate)
public static void goShopping()throws
MoneyLostException,FireException{
}
M2 try_catch
2.11.2 定义异常类
Throwable
Error
AssertionError(断言异常)
OutofMemoryError
Exception
RuntimeException
ArrayIndexOutofBoundsException
ArithmeticException
NullPointerException
SQLException
IOException
FileNotFoundException
(1) 异常类
public static void test(){
int x,y;
x=y=0;
// System.out.println(x/y);//ArithmeticException
Object o=null;
// System.out.println(o.toString());//NullPointerException
Mammal1 m=new Person();
// Dog d=(Dog)m;//ClassCastException
int a[]=new int[5];
// System.out.println(a[5]);//ArrayIndexOutofBoundsException
}
(2)定义异常类
class MoneyLostException extends Exception{
private String addr;
private String cause;
private float money;
private Date date;
public MoneyLostException(String addr,String cause,float money,String date)throws ParseException{
this.addr=addr;
this.cause=cause;
this.money=money;
DateFormat df=DateFormat.getDateTimeInstance();
this.date=df.parse(date);//”2009-99”
}
public String toString(){//toString is method of Object
return"Money("+money+") lost"+" on "+addr+" on "+date+" because of "+cause;
}
}
class FireException extends Exception{
private String addr;
private String cause;
// private float money;
private Date date;
public FireException(String addr,String cause,String date)throws ParseException{
this.addr=addr;
this.cause=cause;
// this.money=money;
DateFormat df=DateFormat.getDateTimeInstance();
this.date=df.parse(date);
}
public String toString(){
return"Fire "+" on "+addr+" on "+date+" because of "+cause;
}
}
2.11.3 抛出异常类
public static void goShopping(int cmd)throws
MoneyLostException,FireException,ParseException{
switch(cmd){
case 1:
FireException e=new FireException("Sanhao street","smoking","2009-9-9 13:45:45");
throw e;
case 2:
MoneyLostException e1=new MoneyLostException("Sanhao street","smoking",500,"2009-9-9 13:45:45");
throw e1;
default:
System.out.println("God blessing");
}
System.out.println("End of Shopping");
}
2.11.4 捕获
public static void main(String[] args){
// TODO Auto-generated method stub
// test();
try{
goShopping(0);
System.out.println("----------");
}
catch(MoneyLostException e){
System.out.println(e)
System.out.println("After all,tomorrow is another day");
}
catch(FireException e){
System.out.println(e);
System.out.println("Escape right now");
}
catch(ParseException e){
System.out.println(e);
System.out.println("Correct date format .");
}
System.out.println("The End ");
}
2.11.5 Override时的异常处理
例:
package com.jida.ex1;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class ExceptionTest1 {
public static void main(String s[]){
int x=0,y=0;
// System.out.println(x/y);
int a[]=new int[5];
// System.out.println(a[5]);
Object obj=null;
// System.out.println(obj.toString());
try{
goShopping(3);
}
catch(MoneyLostException e){
}
catch(FireException e){
}
catch(ParseException e){
}
}
public static void goShopping(int cmd)throws ParseException,MoneyLostException ,FireException{
switch(cmd){
case 1:
MoneyLostException e=new MoneyLostException("商业城","被偷","2009-3-3 15:35:56",500);
throw e;
case 2:
FireException e1=new FireException("商业城","吸烟","2008-3-9 15:35:56");
throw e1;
default:
System.out.println("God blessing");
}
System.out.println("End of shopping");
}
}
class MoneyLostException extends Exception{
private String addr;
private Date date;
private String cause;
private float amount;
public MoneyLostException(String addr,String cause,String date,float amount)throws ParseException{
this.addr=addr;
this.cause=cause;
this.amount=amount;
DateFormat df=DateFormat.getDateTimeInstance();
this.date=df.parse(date);
}
public String toString(){
return "Money ("+amount+") lost on "+date+" on " +addr+" bacause of "+cause;
}
}
class FireException extends Exception{
private String addr;
private Date date;
private String cause;
// private float amount;
public FireException(String addr,String cause,String date)throws ParseException{ this.addr=addr;
this.cause=cause;
// this.amount=amount;
DateFormat df=DateFormat.getDateTimeInstance();
this.date=df.parse(date);
}
public String toString(){
return "Fire on "+date+" on " +addr+" bacause of "+cause;
}
}
2.12 内部类(1)
2.12.1 Static Inner Class
2.12.2 Member Inner Class
2.12.3 Local Inner Class
2.12.4 Anonymous Inner Class
public class En {
String sec="hu";
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
En.StaticInnerClass sin=new En.StaticInnerClass();
En en=new En();
En.MemberInnerClass min=en.new MemberInnerClass();
en.c1.f();
}
protected static class StaticInnerClass{
}
public class MemberInnerClass{
String sec="jiang";
void f(){
String sec="liu";
System.out.println(sec+"-"+this.sec+"-"+En.this.sec);
}
}
void f(){
class LocalInnerClass{
void f(){
}
}
new LocalInnerClass().f();
}
C1 c1=new C1(){
void f(){
System.out.println("f in :C1");
}
};
}
class C1{
void f(){
System.out.println(" f in C1");
}
}
2.13 接口(2)
(1) 概念
(2) 接口继承
例2.13 Idiot找会计算的人帮助计算, 先雇用,后测试.
public class Idiot {
private Computable s1,s2;
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Server01 li=new Server01("li");
Server02 liu=new Server02("liu");
Idiot idiot=new Idiot();
idiot.set(li, liu);
idiot.test(3000,4);
}
public void test(int x,int y){
test(x,y,'+');
test(x,y,'-');
test(x,y,'*');
test(x,y,'/');
test(x,y,'~');
}
public void test(int x,int y,char type){
System.out.println(""+x+type+y+"="+pute(x, y, type));
System.out.println(""+x+type+y+"="+pute(x, y, type));
}
public void set(Computable s1,Computable s2){
this.s1=s1;
this.s2=s2;
}
}
interface Computable{
public int compute(int x,int y,char type);
}
class Server01 implements Computable{
private String name;
public Server01 (String name){
=name;
}
public int compute(int x,int y,char type){
switch(type){
case'+': return x+y;
case'-': return x-y;
case'*': return x*y;
case'/': return x/y;
default: System.out.println("Sorry,"+name+" cannot compute "+type);
return 0;
}
}
}
class Server02 implements Computable{
private String name;
public Server02 (String name){
=name;
}
public int compute(int x,int y,char type){
switch(type){
case'+': return x+y;
case'-': return x-y;
case'*': return x*y;
case'/': return x/y;
case'~': return (int)(Math.log(x)/Math.log(y));
default: System.out.println("Sorry,"+name+" cannot compute "+type);
return 0;
}
}
}
package com.jida.ex1;
public class RMBTrans {
public static String [] str1s={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
public static String [] str2s={"","拾","佰","仟"};
public static String [] str3s={"圆","万","亿"};
private BitDesc[] resInt;
private String intStr;
private String floatStr;
private String str;
/**
*@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RMBTrans r=new RMBTrans();
r.setStr("123456000.45");
}
public void split(){
int index=str.indexOf('.');
if(index<0){
intStr=str;
floatStr=null;
}
else{
intStr=str.substring(0,index);
floatStr=str.substring(index+1);
}
}
public void parseInt(){
int len=intStr.length();
resInt=new BitDesc[len];
for(int i=0;i<len;i++){
resInt[i]=new BitDesc(intStr.charAt(i)-'0',len-1-i);
}
}
public void display(){
for(int i=0;i<resInt.length;i++){
System.out.print(resInt[i].toString());
}
System.out.println();
}
public void setStr(String str){
this.str=str;
split();
parseInt();
display();
}
}
class BitDesc{
private int val;
private int index;
private String str1,str2,str3;
BitDesc(int val,int index){
str1=RMBTrans.str1s[val];
str2=val!=0?RMBTrans.str2s[index%4]:"";
str3=index%4==0?RMBTrans.str3s[index/4]:"";
}
public String toString(){
return str1+str2+str3;
}
}
习题
习题3.1 五子棋期盘描述
习题3.2 单例、多例和枚举
习题3.3 异常练习
习题3.4 人民币小写到大写的转换
第4章GUI编程(5)
4.1 组件
4.2 布局
4.3 事件处理
生产监听器---具体事件处理功能组件注册监听器---注册监听器的组件产生事件源,并将事件对象返回给监听器----监听器调用方法处理事件
(1) 事件(event)与事件驱动
(2) 代理机制
(3) 事件类与处理接口
例4.1 按钮事件处理
例4.2 鼠标轨迹跟踪
例4.3 计算器
例4.4 五子棋程序
4.4 绘图
例4.5 小小CAD
习题
习题4.1 带小数位的计算器的设计与实现
习题4.2 五子棋人机对弈系统的设计与实现
习题4.3 幸运52游戏程序的设计与实现
GUI 计算器
第5章Thread类(3学时)
5.1 线程概念
Process进程,执行的程序
Thread:CPU管理的基本单位,包括执行的代码
5.2 创建线程
Java虚拟机---main函数主线程
CPU---分时多任务---20毫秒时间片
-----=优先级程序大小---排序
使用接口:Runnable
继承Thread
线程状态---静止---running---runnable--挂起(系统只有一个sleep时间到回来---IO阻塞)
---lock pool(每个对象都有---synchronized线程保护---lockpool等待--)---waiting pool (o.wait()---o.notify()---抢锁)
例5.1 创建线程
5.3 线程同步
例5.2 二个人和一个帐户
5.4 线程通讯
例5.3 生产者和消费者习题
习题5.1 线程池的设计与实现
习题5.2 任意个生产者与消费者通讯程序的实现
习题5.3
public class Threads1 {
int x = 0;
public class Runner implements Runnable {
public void run() {
int current = 0;
for (int i = 0; i < 4; i++) {
current = x;
System.out.print(current + ", ");
x = current + 2;
}
}
}
吉大教育
public static void main(String [] args) {
new Threads1().go();
}
public void go() {
Runnable r = new Runner();
new Thread(r).start();
new Thread(r).start();
}
}
Which two are possible results? (choose two)
A. 0, 2, 4, 4, 6, 8, 10, 6,
B. 0, 2, 4, 6, 8, 10, 2, 4,
C. 0, 2, 4, 6, 8, 10, 12, 14,
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
E. 0, 2, 4, 6, 8, 10,12,14, 0, 2, 4, 6, 8, 10,12,14,
习题5.4
1.public class TestFive {
2. private int x;
3. public void foo() {
4. int current = x;
5. x = current + 1;
6. }
7. public void go() {
8. for (int i = 0; i < 5; i++) {
9. new Thread() {
10. public void run() {
11. foo();
12. System.out.println(x + ", " );
13. }
14. }.start();
}
}
}
Which two changes taken together, would generate the output 1, 2, 3, 4, 5, ?
A. move the line 12 print statement inoto the foo() method
B. change line 7 to public synchronized void go() {
C. change the variable declaration on line 2 to private volatile int x;
D. wrap the code inside the foo() method with a synchronized(this) block
E. wrap the loop code inside the go() method with a synchronized block synchronized(this) {}。