《Java从入门到精通》src9-25
find . -name *.java |xargs -i sh -c "echo {};cat {}" > ../all.java[op@TIM src]$ cat all.java ./ch09/���渚�9-1/浠g��9-1.java class Person { String name ; int age ; void talk() { System.out.println("我是:"+name+",今年:"+age+"岁"); } } ./ch09/���渚�9-10/浠g��9-10.java class Person { private String name ; private int age ; public Person(String n,int a) { name = n ; age = a ; System.out.println("public Person(String n,int a)") ; } public String talk() { return "我是:"+name+",今年:"+age+"岁" ; } } public class TestConstruct1 { public static void main(String[] args) { Person p = new Person("张三",25) ; System.out.println(p.talk()) ; } } ./ch09/���渚�9-11/浠g��9-11.java class Person { private String name ; private int age ; public Person(String n,int a) { name = n ; age = a ; System.out.println("public Person(String n,int a)") ; } public String talk() { return "我是:"+name+",今年:"+age+"岁" ; } } public class TestConstruct2 { public static void main(String[] args) { Person p = new Person() ; System.out.println(p.talk()) ; } } ./ch09/���渚�9-12/浠g��9-12.java class Person { private String name ; private int age ; public Person() {} public Person(String n,int a) { name = n ; age = a ; System.out.println("public Person(String n,int a)") ; } public String talk() { return "我是:"+name+",今年:"+age+"岁" ; } } public class TestConstruct2 { public static void main(String[] args) { Person p = new Person() ; System.out.println(p.talk()) ; } } ./ch09/���渚�9-13/浠g��9-13.java public class TestSingleDemo1 { private TestSingleDemo1() { System.out.println("private TestSingleDemo1 .") ; } public static void main(String[] args) { new TestSingleDemo1() ; } } ./ch09/���渚�9-14/浠g��9-14.java class Person { String name ; // 在本类声明一Person对象p,注意此对象用final标记,表示不能再重新实例化 private static final Person p = new Person() ; private Person() { name = "张三" ; } public static Person getP() { return p ; } } public class TestSingleDemo2 { public static void main(String[] args) { // 声明一Person类的对象 Person p = null ; p = Person.getP() ; System.out.println(p.name) ; } } ./ch09/���渚�9-15/浠g��9-15.java class Person { private String name ; private int age ; private void talk() { System.out.println("我是:"+name+",今年:"+age+"岁"); } public void say() { talk(); } public void setName(String str) { name = str ; } public void setAge(int a) { if(a>0) age = a ; } public String getName() { return name ; } public int getAge() { return age ; } } public class TestPersonDemo5 { public static void main(String[] args) { // 声明并实例化一Person对象p Person p = new Person() ; // 给p中的属性赋值 p.setName("张三") ; // 在这里将p对象中的年龄属性赋值为-25岁 p.setAge(30) ; // 调用Person类中的say()方法 p.say() ; } } ./ch09/���渚�9-2/浠g��9-2.java class colordefine { String color = "黑色"; void getMes() { System.out.println("定义类"); } public static void main(String args[]) { { colordefine b = new colordefine(); System.out.println(b.color); b.getMes(); } } } ./ch09/���渚�9-3/浠g��9-3.java // 下面这个范例说明了使用Person类的对象调用类中的属性与方法的过程 class TestPersonDemo { public static void main(String[] args) { Person p = new Person() ; p.name = "张三" ; p.age = 25 ; p.talk(); } } ./ch09/���渚�9-4/浠g��9-4.java public class TestEquals { public static void main(String[] args) { String str1 = new String("java") ; String str2 = new String("java") ; String str3 = str2 ; if(str1==str2) { System.out.println("str1 == str2"); } else { System.out.println("str1 != str2") ; } if(str2==str3) { System.out.println("str2 == str3"); } else { System.out.println("str2 != str3") ; } } } ./ch09/���渚�9-5/浠g��9-5.java public class TestEquals1 { public static void main(String[] args) { String str1 = new String("java") ; String str2 = new String("java") ; String str3 = str2 ; if(str1.equals(str2)) { System.out.println("str1 equals str2"); } else { System.out.println("str1 not equals str2") ; } if(str2.equals(str3)) { System.out.println("str2 equals str3"); } else { System.out.println("str2 note equals str3") ; } } } ./ch09/���渚�9-6/浠g��9-6.java class Person { String name ; int age ; public Person() { } public Person(String name,int age) { this.name = name ; this.age = age ; } public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁" ; } } public class TestObjectArray { public static void main(String[] args) { Person p[] = { new Person("张三",25),new Person("李四",30),new Person("王五",35) } ; for(int i=0;i<p.length;i++) { System.out.println(p[i].talk()) ; } } } ./ch09/���渚�9-7/浠g��9-7.java public class Test { static String a = "string-a"; static String b; String c = "stirng-c"; String d; static { printStatic("before static"); b = "string-b"; printStatic("after static"); } public static void printStatic(String title) { System.out.println("---------" + title + "---------"); System.out.println("a = \"" + a + "\""); System.out.println("b = \"" + b + "\""); } public Test() { print("before constructor"); d = "string-d"; print("after constructor"); } public void print(String title) { System.out.println("---------" + title + "---------"); System.out.println("a = \"" + a + "\""); System.out.println("b = \"" + b + "\""); System.out.println("c = \"" + c + "\""); System.out.println("d = \"" + d + "\""); } public static void main(String[] args) { new Test(); } }./ch09/���渚�9-8/浠g��9-8.java public class methoddemo { int a = 12345679 , b =81; public void times(int i, int j) { System.out.println(i*j); } public static void main(String args[]) { methoddemo m = new methoddemo(); m.times(m.a, m.b); } } ./ch09/���渚�9-9/浠g��9-9.java class Person { public Person() // Person类的构造方法 { System.out.println("public Person()") ; } } public class TestConstruct { public static void main(String[] args) { Person p = new Person() ; } } ./ch09/璺����涓����/Xiti_9/src/Person.java class Person { String name ; int age ; String like; void talk() { System.out.println("我是:"+name+",今年:"+age+"岁,"+ "喜欢:"+ like); } } ./ch09/璺����涓����/Xiti_9/src/Xiti_9.java // 下面这个范例说明了使用Person类的对象调用类中的属性与方法的过程 class Xiti_9 { public static void main(String[] args) { Person p = new Person() ; p.name = "张三" ; p.age = 25 ; p.like= "音乐和诗歌"; p.talk(); } } ./ch10/���渚�10-1/浠g��10-1.java class Person { String name ; int age ; void talk() { System.out.println("我是:"+name+",今年:"+age+"岁"); } } public class TestPersonDemo2 { public static void main(String[] args) { // 声明并实例化一Person对象p Person p = new Person() ; // 给p中的属性赋值 p.name = "张三" ; // 在这里将对象p的年龄属性赋值为-25岁 p.age = -25 ; // 调用Person类中的talk()方法 p.talk() ; } } ./ch10/���渚�10-10/浠g��10-10.java class Person { String name ; int age ; public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁"; } } class Student extends Person { String school ; public Student(String name,int age,String school) { // 分别为属性赋值 this.name = name ; this.age = age ; this.school = school ; } // 此处覆写Person中的talk()方法 public String talk() { return "我在"+this.school+"上学" ; } } class TestOverDemo1 { public static void main(String[] args) { Student s = new Student("张三",25,"北京") ; // 此时调用的是子类中的talk()方法 System.out.println(s.talk()) ; } } ./ch10/���渚�10-11/浠g��10-11.java class Person { String name ; int age ; public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁"; } } class Student extends Person { String school ; public Student(String name,int age,String school) { // 分别为属性赋值 this.name = name ; this.age = age ; this.school = school ; } // 此处覆写Person类中的talk()方法 public String talk() { return super.talk()+",我在"+this.school+"上学" ; } } class TestOverDemo2 { public static void main(String[] args) { Student s = new Student("张三",25,"北京") ; //此时调用的是子类中的talk()方法 System.out.println(s.talk()) ; } } ./ch10/���渚�10-12/浠g��10-12.java class Person { public void fun1() { System.out.println("1.Person{fun1()}") ; } public void fun2() { System.out.println("2.Person{fun2()}") ; } } // Student类扩展自Person类,也就继承了Person类中的fun1()、fun2()方法 class Student extends Person { // 在这里覆写了Person类中的fun1()方法 public void fun1() { System.out.println("3.Student{fun1()}") ; } public void fun3() { System.out.println("4.Studen{fun3()}") ; } } class TestJavaDemo1 { public static void main(String[] args) { // 此处,父类对象由子类实例化 Person p = new Student() ; // 调用fun1()方法,观察此处调用的是哪个类里的fun1()方法 p.fun1() ; p.fun2() ; } } ./ch10/���渚�10-13/浠g��10-13.java class Person { public void fun1() { System.out.println("1.Person{fun1()}") ; } public void fun2() { System.out.println("2.Person{fun2()}") ; } } // Student类继承Person类,也就继承了Person类的fun1()、fun2()方法 class Student extends Person { // 在这里覆写了Person类中的fun1()方法 public void fun1() { System.out.println("3.Student{fun1()}") ; } public void fun3() { System.out.println("4.Studen{fun3()}") ; } } class TestJavaDemo2 { public static void main(String[] args) { // 此处,父类对象由自身实例化 Person p = new Person() ; // 将p对象向下转型 Student s = (Student)p ; p.fun1() ; p.fun2() ; } } ./ch10/���渚�10-2/浠g��10-2.java class Person { private String name ; private int age ; void talk() { System.out.println("我是:"+name+",今年:"+age+"岁"); } } public class TestPersonDemo3_1 { public static void main(String[] args) { // 声明并实例化一Person对象p Person p = new Person() ; // 给p中的属性赋值 p.name = "张三" ; // 在这里将p对象中的年龄赋值为-25岁 p.age = -25 ; // 调用Person类中的talk()方法 p.talk() ; } } ./ch10/���渚�10-3/浠g��10-3.java class Person { private String name ; private int age ; void talk() { System.out.println("我是:"+name+",今年:"+age+"岁"); } public void setName(String str) { name = str ; } public void setAge(int a) { if(a>0) age = a ; } public String getName() { return name ; } public int getAge() { return age ; } } public class TestPersonDemo3-2 { public static void main(String[] args) { // 声明并实例化一Person对象p Person p = new Person() ; // 给p中的属性赋值 p.setName("张三") ; // 在这里将p对象中的年龄赋值为-25岁 p.setAge(-25) ; // 调用Person类中的talk()方法 p.talk() ; } } ./ch10/���渚�10-4/浠g��10-4.java class Person { private String name ; private int age ; private void talk() { System.out.println("我是:"+name+",今年:"+age+"岁"); } public void setName(String str) { name = str ; } public void setAge(int a) { if(a>0) age = a ; } public String getName() { return name ; } public int getAge() { return age ; } } public class TestPersonDemo4 { public static void main(String[] args) { // 声明并实例化一Person对象p Person p = new Person() ; // 给p中的属性赋值 p.setName("张三") ; // 在这里将p对象中的年龄赋值为-25岁 p.setAge(-25) ; // 调用Person类中的talk()方法 p.talk() ; } } ./ch10/���渚�10-5/浠g��10-5.java class Person { String name ; int age ; } class Student extends Person { String school ; } public class TestPersonStudentDemo { public static void main(String[] args) { Student s = new Student() ; // 访问Person类中的name属性 s.name = "张三" ; // 访问Person类中的age属性 s.age = 25 ; // 访问Student类中的school属性 s.school = "北京" ; System.out.println("姓名:"+s.name+",年龄:"+s.age+",学校:"+s.school) ; } } ./ch10/���渚�10-6/浠g��10-6.java class Person { String name ; int age ; // 父类的构造方法 public Person() { System.out.println("1.public Person(){}") ; } } class Student extends Person { String school ; // 子类的构造方法 public Student() { System.out.println("2.public Student(){}"); } } public class TestPersonStudentDemo1 { public static void main(String[] args) { Student s = new Student() ; } } ./ch10/���渚�10-7/浠g��10-7.java class Person { String name ; int age ; // 父类的构造方法 public Person(String name,int age) { this.name = name ; this.age = age ; } } class Student extends Person { String school ; // 子类的构造方法 public Student() { // 在这里用super调用父类中的构造方法 super("张三",25); } } public class TestPersonStudentDemo2 { public static void main(String[] args) { Student s = new Student() ; // 为Student类中的school赋值 s.school = "北京" ; System.out.println("姓名:"+s.name+",年龄:"+s.age+",学校:"+s.school) ; } } ./ch10/���渚�10-8/浠g��10-8.java class Person { String name ; int age ; // 父类的构造方法 public Person() { } public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁" ; } } class Student extends Person { String school ; // 子类的构造方法 public Student(String name,int age,String school) { // 在这里用super调用父类中的属性 super.name = name ; super.age = age ; // 调用父类中的talk()方法 System.out.print(super.talk()); // 调用本类中的school属性 this.school = school ; } } public class TestPersonStudentDemo3 { public static void main(String[] args) { Student s = new Student("张三",25,"北京") ; System.out.println(",学校:"+s.school) ; } }姓名:张三,年龄:25,学校:北京 ./ch10/���渚�10-9/浠g��10-9.java class Person { // 在这里将属性封装 private String name ; private int age ; } class Student extends Person { // 在这里访问父类中被封装的属性 public void setVar() { name = "张三" ; age = 25 ; } } class TestPersonStudentDemo4 { public static void main(String[] args) { new Student().setVar() ; } } ./ch10/璺����涓����/Xiti_10.java class Person { String name ; int age ; String like; public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁"; } } class Student extends Person { String school ; public Student(String name,int age,String like) { // 分别为属性赋值 this.name = name ; this.age = age ; this.like = like ; } // 此处覆写Person中的talk()方法 public String talk() { return "我喜欢"+this.like ; } } class Xiti_10 { public static void main(String[] args) { Student s = new Student("张三",25,"音乐") ; // 此时调用的是子类中的talk()方法 System.out.println(s.talk()) ; } } ./ch11/���渚�11-1/浠g��11-1.java abstract class Person { String name ; int age ; String occupation ; // 声明一抽象方法talk() public abstract String talk() ; } // Student类继承自Person类 class Student extends Person { public Student(String name,int age,String occupation) { this.name = name ; this.age = age ; this.occupation = occupation ; } // 覆写talk()方法 public String talk() { return "学生――>姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!" ; } } // Worker类继承自Person类 class Worker extends Person { public Worker(String name,int age,String occupation) { this.name = name ; this.age = age ; this.occupation = occupation ; } // 覆写talk()方法 public String talk() { return "工人――>姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!" ; } } class TestAbstractDemo1 { public static void main(String[] args) { Student s = new Student("张三",20,"学生") ; Worker w = new Worker("李四",30,"工人") ; System.out.println(s.talk()) ; System.out.println(w.talk()) ; } } ./ch11/���渚�11-2/浠g��11-2.java abstract class Person { String name ; int age ; String occupation ; public Person(String name,int age,String occupation) { this.name = name ; this.age = age ; this.occupation = occupation ; } public abstract String talk() ; } class Student extends Person { public Student(String name,int age,String occupation) { // 在这里必须明确调用抽象类中的构造方法 super(name,age,occupation); } public String talk() { return "学生――>姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!" ; } } class TestAbstractDemo2 { public static void main(String[] args) { Student s = new Student("张三",20,"学生") ; System.out.println(s.talk()) ; } } ./ch11/���渚�11-3/浠g��11-3.java interface Person { String name = "张三"; int age = 25 ; String occupation = "学生" ; // 声明一抽象方法talk() public abstract String talk() ; } // Student类实现自Person类 class Student implements Person { // 覆写talk()方法 public String talk() { return "学生――>姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!" ; } } class TestInterfaceDemo1 { public static void main(String[] args) { Student s = new Student() ; System.out.println(s.talk()) ; } } ./ch11/���渚�11-4/浠g��11-4.java interface A { int i = 10 ; public void sayI() ; } interface E { int x = 40 ; public void sayE() ; } // B同时继承了A、E两个接口 interface B extends A,E { int j = 20 ; public void sayJ() ; } // C继承实现B接口,也就意味着要实现A、B、E三个接口的抽象方法 class C implements B { public void sayI() { System.out.println("i = "+i); } public void sayJ() { System.out.println("j = "+j) ; } public void sayE() { System.out.println("e = "+x); } } class TestInterfaceDemo2 { public static void main(String[] args) { C c = new C() ; c.sayI() ; c.sayJ() ; } } ./ch11/璺����涓����/Xiti_11.java abstract class Person { String name ; int age ; String occupation ; // 声明一抽象方法talk() public abstract String talk() ; } // Official类继承自Person类 class Official extends Person { public Official(String name,int age,String occupation) { this.name = name ; this.age = age ; this.occupation = occupation ; } // 覆写talk()方法 public String talk() { return "干部――>姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!" ; } } // Worker类继承自Person类 class Worker extends Person { public Worker(String name,int age,String occupation) { this.name = name ; this.age = age ; this.occupation = occupation ; } // 覆写talk()方法 public String talk() { return "工人――>姓名:"+this.name+",年龄:"+this.age+",职业:"+this.occupation+"!" ; } } class Xiti_11 { public static void main(String[] args) { Official s = new Official("李乐乐",20,"干部") ; Worker w = new Worker("工作",30,"工人") ; System.out.println(s.talk()) ; System.out.println(w.talk()) ; } } ./ch12/���渚�12-14/浠g��12-14.java // 以下程序是关于方法的返回类型是整型的范例 public class TestJavafanhuizhengxing { public static void main(String args[]) { int num; num=star(7); // 输入7给star(),并以num接收返回的数值� System.out.println(num+" stars printed"); } public static int star(int n) // star() method { for(int i=1;i<=2*n;i++) System.out.print("*"); // 输出2*n个星号 System.out.print("\n"); // 换行 return 2*n; // 返回整数2*n } } ./ch12/���渚�12-1/浠g��12-1.java class Person extends Object { String name = "张三"; int age = 25 ; } class TestToStringDemo1 { public static void main(String[] args) { Person p = new Person() ; System.out.println(p); } } ./ch12/���渚�12-10/浠g��12-10.java interface A { public void fun1() ; } class B { int i = 10 ; class C implements A { public void fun1() { System.out.println(i) ; } } public void get(A a) { a.fun1() ; } public void test() { this.get(new C()) ; } } class TestNonameInner1 { public static void main(String[] args) { B b = new B() ; b.test() ; } } ./ch12/���渚�12-11/浠g��12-11.java interface A { public void fun1() ; } class B { int i = 10 ; public void get(A a) { a.fun1() ; } public void test() { this.get(new A() { public void fun1() { System.out.println(i) ; } } ) ; } } class TestNonameInner2 { public static void main(String[] args) { B b = new B() ; b.test() ; } } ./ch12/���渚�12-12/浠g��12-12.java class Person { private String name = "张三" ; private int age = 25 ; public String talk() { return "我是:"+name+",今年:"+age+"岁" ; } } public class TestNoName { public static void main(String[] args) { System.out.println(new Person().talk()); } } ./ch12/���渚�12-13/浠g��12-13.java // 以下程序主要说明如何去声明并使用一个方法 public class TestJavashengming { public static void main(String args[]) { star(); // 调用star() 方法 System.out.println("I Like Java !"); star(); // 调用star() 方法 } public static void star() // star() 方法 { for(int i=0;i<19;i++) System.out.print("*"); // 输出19个星号 System.out.print("\n"); // 换行 } } ./ch12/���渚�12-15/浠g��12-15.java // 以下的程序说明了方法的使用 public class TestJavafangfa { public static void main(String args[]) { double num; num=show_length(22,19); // 输入22与19两个参数到show_length()里 System.out.println("对角线长度 = "+num); } public static double show_length(int m, int n) { return Math.sqrt(m*m+n*n); // 返回对角线长度� } } ./ch12/���渚�12-16/浠g��12-16.java // 以下程序说明了方法的重载操作 public class TestJavareload { public static void main(String[] args) { int int_sum ; double double_sum ; int_sum = add(3,5) ; // 调用有两个参数的add方法 System.out.println("int_sum = add(3,5)的值是:"+int_sum); int_sum = add(3,5,6) ; // 调用有三个参数的add方法 System.out.println("int_sum = add(3,5,6)的值是:"+int_sum); double_sum = add(3.2,6.5); // 传入的数值为doule类型 System.out.println("double_sum = add(3.2,6.5)的值是:"+double_sum); } public static int add(int x,int y) { return x+y ; } public static int add(int x,int y,int z) { return x+y+z ; } public static double add(double x,double y) { return x+y ; } } ./ch12/���渚�12-17/浠g��12-17.java // 一维数组作为参数来传递,这里的一维数组采用静态方式赋值 public class TestJavachuanshuzu { public static void main(String args[]) { int score[]={7,3,8,19,6,22}; // 声明一个一维数组score largest(score); // 将一维数组score传入largest() 方法中 } public static void largest(int arr[]) { int tmp=arr[0]; for(int i=0;i<arr.length;i++) if(tmp<arr[i]) tmp=arr[i]; System.out.println("最大的数 = "+tmp); } } ./ch12/���渚�12-18/浠g��12-18.java // 以下程序说明了如何将一个二维数组作为参数传递到方法中 public class TestJavachuanerwei { public static void main(String args[]) { int A[][] = {{51,38,22,12,34},{72,64,19,31}} ; // 定义一个二维数组A print_mat(A); } public static void print_mat(int arr[][]) // 接收整数类型的二维数组 { for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) System.out.print(arr[i][j]+" "); // 输出数组值� System.out.print("\n"); // 换行 } } } ./ch12/���渚�12-19/浠g��12-19.java // 以下的程序说明了方法中返回一个二维数组的实现过程 public class TestJavafanerwei { public static void main(String args[]) { int A[][]={{51,38,82,12,34},{72,64,19,31}}; // 定义二维数组 int B[][]=new int[2][5]; B=add10(A); // 调用add10(),并把返回的值设给数组B for(int i=0;i<B.length;i++) // 输出数组的内容 { for(int j=0;j<B[i].length;j++) System.out.print(B[i][j]+" "); System.out.print("\n"); } } public static int[][] add10(int arr[][]) { for(int i=0;i<arr.length;i++) for(int j=0;j<arr[i].length;j++) arr[i][j]+=10; // 将数组元素加10 return arr; // 返回二维数组 } } ./ch12/���渚�12-2/浠g��12-2.java class Person extends Object { String name = "张三"; int age = 25 ; // 覆写Object类中的toString()方法 public String toString() { return "我是:"+this.name+",今年:"+this.age+"岁"; } } class TestToStringDemo2 { public static void main(String[] args) { Person p = new Person() ; System.out.println(p); } } ./ch12/���渚�12-20/浠g��12-20.java class Person { String name ; int age ; } public class TestRefDemo1 { public static void main(String[] args) { // 声明一对象p1,此对象的值为null,表示未实例化 Person p1 = null ; // 声明一对象p2,此对象的值为null,表示未实例 Person p2 = null ; // 实例化p1对象 p1 = new Person() ; // 为p1对象中的属性赋值 p1.name = "张三" ; p1.age = 25 ; // 将p1的引用赋给p2 p2 = p1 ; // 输出p2对象中的属性 System.out.println("姓名:"+p2.name); System.out.println("年龄:"+p2.age); p1 = null ; } } ./ch12/���渚�12-21/浠g��12-21.java class Change { int x = 0 ; } public class TestRefDemo2 { public static void main(String[] args) { Change c = new Change() ; c.x = 20 ; fun(c) ; System.out.println("x = "+c.x); } public static void fun(Change c1) { c1.x = 25 ; } } ./ch12/���渚�12-22/浠g��12-22.java class Person { private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } } class TestOverEquals1 { public static void main(String[] args) { Person p1 = new Person("张三",25); Person p2 = new Person("张三",25); // 判断p1和p2的内容是否相等 System.out.println(p1.equals(p2)?"是同一个人!":"不是同一个人"); } } ./ch12/���渚�12-23/浠g��12-23.java class Person { private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } // 覆写父类(Object类)中的equals方法 public boolean equals(Object o) { boolean temp = true ; // 声明一p1对象,此对象实际上就是当前调用equals方法的对象 Person p1 = this ; // 判断Object类对象是否是Person的实例 if(o instanceof Person) { // 如果是Person类实例,则进行向下转型 Person p2 = (Person)o ; // 调用String类中的equals方法 if(!(p1.name.equals(p2.name)&&p1.age==p2.age)) { temp = false ; } } else { // 如果不是Person类实例,则直接返回false temp = false ; } return temp ; } } class TestOverEquals2 { public static void main(String[] args) { Person t_p1 = new Person("张三",25); Person t_p2 = new Person("张三",25); // 判断p1和p2的内容是否相等 System.out.println(t_p1.equals(t_p2)?"是同一个人!":"不是同一个人"); } } ./ch12/���渚�12-24/浠g��12-24.java interface Person { public void fun1() ; } class Student implements Person { public void fun1() { System.out.println("Student fun1()"); } } class TestInterfaceObject { public static void main(String[] args) { Person p = new Student() ; p.fun1() ; } } ./ch12/���渚�12-25/浠g��12-25.java interface Usb { public void start() ; public void stop() ; } class MoveDisk implements Usb { public void start() { System.out.println("MoveDisk start...") ; } public void stop() { System.out.println("MoveDisk stop...") ; } } class Mp3 implements Usb { public void start() { System.out.println("Mp3 start...") ; } public void stop() { System.out.println("Mp3 stop...") ; } } class Computer { public void work(Usb u) { u.start() ; u.stop() ; } } class TestInterface { public static void main(String[] args) { new Computer().work(new MoveDisk()) ; new Computer().work(new Mp3()) ; } } ./ch12/���渚�12-26/浠g��12-26.java class Person { private String name ; private int age ; public Person(String name,int age) { name = name ; age = age ; } } ./ch12/���渚�12-27/浠g��12-27.java class Person-1 { private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } } ./ch12/���渚�12-28/浠g��12-28.java class Person { private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } public String talk() { return "我是:"+name+",今年:"+age+"岁" ; } } public class TestJavaThis { public static void main(String[] args) { Person p = new Person("张三",25) ; System.out.println(p.talk()) ; } } ./ch12/���渚�12-29/浠g��12-29.java class Person { String name ; int age ; Person(String name,int age) { this.name = name ; this.age = age ; } boolean compare(Person p) { if(this.name.equals(p.name)&&this.age==p.age) { return true ; } else { return false ; } } } public class TestCompare { public static void main(String[] args) { Person p1 = new Person("张三",30); Person p2 = new Person("张三",30); System.out.println(p1.compare(p2)?"相等,是同一人!":"不相等,不是同一人!"); } } ./ch12/���渚�12-3/浠g��12-3.java class Outer { int score = 95; void inst() { Inner in = new Inner(); in.display(); } class Inner { void display() { System.out.println("成绩: score = " + score); } } } public class InnerClassDemo { public static void main(String[] args) { Outer outer = new Outer(); outer.inst(); } } ./ch12/���渚�12-30/浠g��12-30.java class Person { String name ; int age ; public Person() { System.out.println("1. public Person()"); } public Person(String name,int age) { // 调用本类中无参构造方法 this() ; this.name = name ; this.age = age ; System.out.println("2. public Person(String name,int age)"); } } public class TestJavaThis1 { public static void main(String[] args) { new Person("张三",25) ; } } ./ch12/���渚�12-31/浠g��12-31.java class Person { String name ; String city ; int age ; public Person(String name, String city, int age) { this.name = name ; this.city = city ; this.age = age ; } public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁,来自:"+this.city; } } public class TestStaticDemo1 { public static void main(String[] args) { Person p1 = new Person("张三","中国",25) ; Person p2 = new Person("李四","中国",30) ; Person p3 = new Person("王五","中国",35) ; System.out.println(p1.talk()) ; System.out.println(p2.talk()) ; System.out.println(p3.talk()) ; } } ./ch12/���渚�12-32/浠g��12-32.java class Person { String name ; static String city = "中国"; int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁,来自:"+city; } } public class TestStaticDemo2 { public static void main(String[] args) { Person p1 = new Person("张三",25) ; Person p2 = new Person("李四",30) ; Person p3 = new Person("王五",35) ; System.out.println("修改之前信息:"+p1.talk()) ; System.out.println("修改之前信息:"+p2.talk()) ; System.out.println("修改之前信息:"+p3.talk()) ; System.out.println(" ************* 修改之后信息 **************"); // 修改后的信息 p1.city = "美国" ; System.out.println("修改之后信息:"+p1.talk()) ; System.out.println("修改之后信息:"+p2.talk()) ; System.out.println("修改之后信息:"+p3.talk()) ; } } ./ch12/���渚�12-33/浠g��12-33.java class Person { String name ; private static String city = "中国"; int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } public String talk() { return "我是:"+this.name+",今年:"+this.age+"岁,来自:"+city; } public static void setCity(String c) { city = c ; } } public class TestStaticDemo3 { public static void main(String[] args) { Person p1 = new Person("张三",25) ; Person p2 = new Person("李四",30) ; Person p3 = new Person("王五",35) ; System.out.println("修改之前信息:"+p1.talk()) ; System.out.println("修改之前信息:"+p2.talk()) ; System.out.println("修改之前信息:"+p3.talk()) ; System.out.println(" **************修改之后信息**************"); // 修改后的信息 Person.setCity("美国") ; System.out.println("修改之后信息:"+p1.talk()) ; System.out.println("修改之后信息:"+p2.talk()) ; System.out.println("修改之后信息:"+p3.talk()) ; } } ./ch12/���渚�12-34/浠g��12-34.java public class TestMain { /* public:表示公共方法 static:表示此方法为一静态方法,可以由类名直接调用 void:表示此方法无返回值 main:系统定义的方法名称 String args[]:接收运行时参数 */ public static void main(String[] args) { // 取得输入参数的长度 int j = args.length ; if(j!=2) { System.out.println("输入参数个数有错误!") ; // 退出程序 System.exit(1) ; } for (int i=0;i<args.length ;i++ ) { System.out.println(args[i]) ; } } } ./ch12/���渚�12-35/浠g��12-35.java class Person { public Person() { System.out.println("1.public Person()"); } // 此段代码会首先被执行 static { System.out.println("2.Person类的静态代码块被调用!"); } } public class TestStaticDemo5 { // 运行本程序时,静态代码块会被自动执行 static { System.out.println("3.TestStaticDemo5类的静态代码块被调用!"); } public static void main(String[] args) { System.out.println("4.程序开始执行!"); // 产生两个实例化对象 new Person() ; new Person() ; } } ./ch12/���渚�12-36/浠g��12-36.java class TestFinalDemo1 { public static void main(String[] args) { final int i = 10 ; // 修改用final修饰的变量i i++ ; } } ./ch12/���渚�12-37/浠g��12-37.java final class Person { } class Student extends Person { } ./ch12/���渚�12-38/浠g��12-38.java class Person { // 此方法声明为final不能被子类覆写 final public String talk() { return "Person:talk()" ; } } class Student extends Person { public String talk() { return "Student:talk()" ; } } ./ch12/���渚�12-39/浠g��12-39.java class Person { public void fun1() { System.out.println("1.Person{fun1()}") ; } public void fun2() { System.out.println("2.Person{fun2()}") ; } } // Student类继承自Person类,也就继承了Person类中的fun1()、fun2()方法 class Student extends Person { // 在这里覆写了Person类中的fun1()方法 public void fun1() { System.out.println("3.Student{fun1()}") ; } public void fun3() { System.out.println("4.Studen{fun3()}") ; } } class TestJavaDemo3 { public static void main(String[] args) { // 声明一父类对象并通过子类对象对其进行实例化 Person p = new Student() ; // 判断对象p是否是Student类的实例 if(p instanceof Student) { // 将Person类的对象p转型为Student类型 Student s = (Student)p ; s.fun1() ; } else { p.fun2() ; } } } ./ch12/���渚�12-4/浠g��12-4.java class Outer { int score = 95; void inst() { Inner in = new Inner(); in.display(); } public class Inner { void display() { // 在内部类中声明一name属性 String name = "张三" ; System.out.println("成绩: score = " + score); } } public void print() { // 在此调用内部类的name属性 System.out.println("姓名:"+name) ; } } public class InnerClassDemo1 { public static void main(String[] args) { Outer outer = new Outer(); outer.inst(); } } ./ch12/���渚�12-5/浠g��12-5.java class Outer { int score = 95; void inst() { Inner in = new Inner(); in.display(); } // 这里用static声明内部类 static class Inner { void display() { System.out.println("成绩: score = " + score); } } } public class InnerClassDemo2 { public static void main(String[] args) { Outer outer = new Outer(); outer.inst(); } } ./ch12/���渚�12-6/浠g��12-6.java class Outer { int score = 95; void inst() { Inner in = new Inner(); in.display(); } public class Inner { void display() { System.out.println("成绩: score = " + score); } } } public class InnerClassDemo3 { public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.display() ; } } ./ch12/���渚�12-7/浠g��12-7.java class Outer { int score = 95; void inst() { class Inner { void display() { System.out.println("成绩: score = " + score); } } Inner in = new Inner(); in.display(); } } public class InnerClassDemo4 { public static void main(String[] args) { Outer outer = new Outer(); outer.inst() ; } } ./ch12/���渚�12-8/浠g��12-8.java class Outer { int score = 95; void inst(final int s) { int temp = 20 ; class Inner { void display() { System.out.println("成绩: score = " + (score+s+temp)); } } Inner in = new Inner(); in.display(); } } public class InnerClassDemo5 { public static void main(String[] args) { Outer outer = new Outer(); outer.inst(5) ; } } ./ch12/���渚�12-9/浠g��12-9.java class Outer { int score = 95; void inst(final int s) { final int temp = 20 ; class Inner { void display() { System.out.println("成绩: score = " + (score+s+temp)); } } Inner in = new Inner(); in.display(); } } public class InnerClassDemo5 { public static void main(String[] args) { Outer outer = new Outer(); outer.inst(5) ; } } ./ch12/璺����涓����/Xiti_12.java class Person { private String name = "张亮亮" ; private int age = 20 ; private String sex = "男"; public String talk() { return "我是:"+name+",今年:"+age+"岁,"+ "我是"+ sex +"性。" ; } } public class Xiti_12 { public static void main(String[] args) { System.out.println(new Person().talk()); } } ./ch13/���渚�13-1/浠g��13-1.java class IntegerDemo { public static void main(String[] args) { String a = "123" ; int i = Integer.parseInt(a) ; i++; System.out.println(i); } } ./ch13/���渚�13-2/浠g��13-2.java import java.util.*; public class SystemInfo { public static void main(String[] args) { Properties sp=System.getProperties(); Enumeration e=sp.propertyNames(); while(e.hasMoreElements()) { String key=(String)e.nextElement(); System.out.println(key+" = "+sp.getProperty(key)); } } } ./ch13/���渚�13-3/浠g��13-3.java public class RuntimeDemo { public static void main(String[] args) { Runtime run = Runtime.getRuntime() ; try { run.exec("notepad.exe") ; } catch (Exception e) { e.printStackTrace(); } } } ./ch13/���渚�13-4/浠g��13-4.java import java.util.*; public class CalendarDemo { public static void main(String[] args) { Calendar c1=Calendar.getInstance(); // 下面打印当前时间 System.out.println(c1.get(c1.YEAR)+"年"+(c1.get(c1.MONTH)+1)+ "月"+c1.get(c1.DAY_OF_MONTH)+"日"+c1.get(c1.HOUR)+ ":"+c1.get(c1.MINUTE)+":"+c1.get(c1.SECOND)); // 增加天数为230 c1.add(c1.DAY_OF_YEAR,230); // 下面打印的是230天后的时间 System.out.println(c1.get(c1.YEAR)+"年"+(c1.get(c1.MONTH)+1)+ "月"+c1.get(c1.DAY_OF_MONTH)+"日"+c1.get(c1.HOUR)+ ":"+c1.get(c1.MINUTE)+":"+c1.get(c1.SECOND)); } } ./ch13/���渚�13-5/浠g��13-5.java import java.text.* ; import java.util.Date; public class DateFormatDemo { public static void main(String[] args) { SimpleDateFormat sp1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") ; SimpleDateFormat sp2 = new SimpleDateFormat("yyyy年MM月dd日 hh点mm分ss秒") ; try { Date d = sp1.parse("2005-8-11 18:30:38") ; System.out.println(sp2.format(d)) ; } catch (ParseException e) { e.printStackTrace(); } } } ./ch13/���渚�13-6/浠g��13-6.java import java.util.Random; public class RandomDemo { public static void main(String[] args) { Random r = new Random() ; for(int i=0;i<5;i++) { System.out.print(r.nextInt(100)+"\t") ; } } } ./ch13/���渚�13-7/浠g��13-7.java import java.util.* ; class Person { private String name ; private int age ; Person(String name,int age) { this.name = name ; this.age = age ; } public String toString() { return "姓名:"+this.name+",年龄:"+this.age ; } } public class HashCodeDemo { public static void main(String args[]) { HashMap hm = new HashMap() ; hm.put(new Person("张三",20),"张三") ; System.out.println(hm.get(new Person("张三",20))) ; } } ./ch13/���渚�13-8/浠g��13-8.java class Employee implements Cloneable { private String name; private int age; public Employee(String name, int age) { this.name = name; this.age = age; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public String toString() { return "姓名:" + this.name + ",年龄:" + this.age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class CloneDemo { public static void main(String args[]) { Employee e1 = new Employee("张三", 21); Employee e2 = null; try { e2 = (Employee) e1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } e2.setName("李四"); e2.setAge(30); System.out.println("两个对象的内存地址比较:" + (e1 == e2)); System.out.println(e1); System.out.println(e2); } } ./ch13/璺����涓����/Xiti_13.java public class Xiti_13 { public static void main(String[] args) { Runtime run = Runtime.getRuntime() ; try { run.exec("calc.exe") ; } catch (Exception e) { e.printStackTrace(); } } } ./ch14/���渚�14-1/浠g��14-1.java package demo.java ; class Person { public String talk() return "Person ―― >> talk()" ; } } class TestPackage1 { public static void main(String[] args) { System.out.println(new Person().talk()) ; } } ./ch14/���渚�14-2/浠g��14-2.java package demo.java.a ; public class Person { public String talk() { return "Person ―― >> talk()" ; } } ./ch14/���渚�14-3/浠g��14-3.java package demo.java.b ; import demo.java.a.Person ; class TestPackage2 { public static void main(String[] args) { System.out.println(new Person().talk()) ; } } ./ch14/���渚�14-4/浠g��14-4.java package demo.java.b ; class TestPackage3 { public static void main(String[] args) { System.out.println(new demo.java.a.Person().talk()) ; } } ./ch14/���渚�14-5/浠g��14-5.java package demo.java.a ; public class Person { protected String name ; public String talk() { return "Person ―― >> talk()" ; } } ./ch14/���渚�14-6/浠g��14-6.java package demo.java.b ; import demo.java.a.* ; public class Student extends Person { public Student(String name) { this.name = name ; } public String talk() { return "Person ―― >> talk() , "+this.name ; } } ./ch14/���渚�14-7/浠g��14-7.java package demo.java.c ; import demo.java.b.* ; class TestPackage4 { public static void main(String[] args) { Student s = new Student("javafans") ; s.name = "javafans" ; System.out.println(s.talk()) ; } } ./ch14/璺����涓����/Xiti_14/src/bao_private/Xiti_14.java package bao_private ; import bao_public.Person ; class Xiti_14 { public static void main(String[] args) { System.out.println(new Person().talk()) ; } } ./ch14/璺����涓����/Xiti_14/src/bao_public/Person.java package bao_public ; public class Person { public String talk() { return "Person ―― >> talk()" ; } } ./ch15/���渚�15-1_/浠g��15-1.java public class TestException_1 { public static void main(String args[]) { int arr[]=new int[5]; // 容许5个元素 arr[10]=7; // 下标值超出所容许的范围 System.out.println("end of main() method !!"); } } ./ch15/���渚�15-2/浠g��15-2.java public class TestException_2 { public static void main(String args[]) { try // 检查这个程序块的代码 { int arr[]=new int[5]; arr[10]=7; // 在这里会出现异常 } catch(ArrayIndexOutOfBoundsException e) { System.out.println("数组超出绑定范围!"); } finally // 这个块的程序代码一定会执行 { System.out.println("这里一定会被执行!"); } System.out.println("main()方法结束!"); } } ./ch15/���渚�15-3/浠g��15-3.java public class TestException_3 { public static void main(String args[]) { try { int arr[]=new int[5]; arr[10]=7; } catch(ArrayIndexOutOfBoundsException e){ System.out.println("数组超出绑定范围!"); System.out.println("异常:"+e); // 显示异常对象e的内容� } System.out.println("main()方法结束!"); } } ./ch15/���渚�15-4/浠g��15-4.java public class TestException_4 { public static void main(String args[]) { int a=4,b=0; try { if(b==0) throw new ArithmeticException("一个算术异常"); // 抛出异常 else System.out.println(a+"/"+b+"="+a/b);// 若抛出异常,则执行此行 } catch(ArithmeticException e) { System.out.println("抛出异常为:"+e); } } } ./ch15/���渚�15-5/浠g��15-5.java class Test { // throws 在指定方法中不处理异常,在调用此方法的地方处理 void add(int a,int b) throws Exception { int c; c=a/b; System.out.println(a+"/"+b+"="+c); } } public class TestException_5 { public static void main(String args[]) { Test t = new Test() ; t.add(4,0); } } ./ch15/���渚�15-6/浠g��15-6.java class DefaultException extends Exception { public DefaultException(String msg) { // 调用Exception类的构造方法,存入异常信息 super(msg) ; } } public class TestException_6 { public static void main(String[] args) { try { // 在这里用throw直接抛出一个DefaultException类的实例对象 throw new DefaultException("自定义异常!") ; } catch(Exception e) { System.out.println(e) ; } } } ./ch15/璺����涓����/Xiti_15.java public class Xiti_15 { public static void main(String args[]) { try // 检查这个程序块的代码 { int x = 6; int y = 0; int z; z = x/y; // 在这里会出现异常 } catch(java.lang.ArithmeticException e) { System.out.println("被除数为0!"); } finally // 这个块的程序代码一定会执行 { System.out.println("程序出错!"); } } } ./ch16/���渚�16-1/浠g��16-1.java import java.util.*; public class ArrayListDemo { public static void main(String args[]) { // 创建一个ArrarList对象 ArrayList al = new ArrayList(); System.out.println("a1 的初始化大小:" + al.size()); // 向ArrayList对象中添加新内容 al.add("C"); // 0位置 al.add("A"); // 1位置 al.add("E"); // 2位置 al.add("B"); // 3位置 al.add("D"); // 4位置 al.add("F"); // 5位置 // 把A2加在ArrayList对象的第2个位置 al.add(1, "A2"); // 加入之后的内容:C A2 A E B D F System.out.println("a1 加入元素之后的大小:" + al.size()); // 显示Arraylist数据 System.out.println("a1 的内容: " + al); // 从ArrayList中移除数据 al.remove("F"); al.remove(2); // C A2 E B D System.out.println("a1 删除元素之后的大小: " + al.size()); System.out.println("a1 的内容: " + al); } } ./ch16/���渚�16-10/浠g��16-10.java import java.util.* ; class Employee implements Comparator { public int compare(Object a, Object b) { int k; String aStr, bStr; aStr = (String) a; bStr = (String) b; k = aStr.compareTo(bStr); if(k==0) return aStr.compareTo(bStr); else return k; } } public class TreeMapDemo2 { public static void main(String args[]) { // 创建一个TreeMap对象 TreeMap tm = new TreeMap(new Employee()); // 向Map对象中插入元素 tm.put("Z、张三", new Double(3534.34)); tm.put("L、李四", new Double(126.22)); tm.put("W、王五", new Double(1578.40)); tm.put("Z、赵六", new Double(99.62)); tm.put("S、孙七", new Double(-29.08)); Set set = tm.entrySet(); Iterator itr = set.iterator(); while(itr.hasNext()) { Map.Entry me = (Map.Entry)itr.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); double balance = ((Double)tm.get("Z、张三")).doubleValue(); tm.put("Z、张三", new Double(balance + 2000)); System.out.println("张三最新的资金数为: " + tm.get("Z、张三")); } } ./ch16/���渚�16-11/浠g��16-11.java import java.util.* ; public class VectorDemo { public static void main(String[] args) { Vector v = new Vector() ; v.add("A") ; v.add("B") ; v.add("C") ; v.add("D") ; v.add("E") ; v.add("F") ; Enumeration e = v.elements() ; while(e.hasMoreElements()) { System.out.print(e.nextElement()+"\t") ; } } } ./ch16/���渚�16-12/浠g��16-12.java import java.util.* ; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("入栈(" + a + ")"); System.out.println("Stack: " + st); } static void showpop(Stack st) { System.out.print("出栈 -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("Stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("Stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); //出栈的时候会有一个EmptyStackException的异常,需要进行异常处理 try { showpop(st); } catch (EmptyStackException e) { System.out.println("出现异常:栈中内容为空"); } } } ./ch16/���渚�16-13/浠g��16-13.java import java.util.* ; public class HashtableDemo { public static void main(String[] args) { Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); Integer n = (Integer) numbers.get("two"); if (n != null) { System.out.println("two = " + n); } } } ./ch16/���渚�16-14/浠g��16-14.java import java.util.*; public class PropertiesDemo { public static void main(String args[]) { Properties capitals = new Properties(); Set states; String str; capitals.put("中国", "北京"); capitals.put("俄罗斯", "莫斯科"); capitals.put("日本", "东京"); capitals.put("法国", "巴黎"); capitals.put("英国", "伦敦"); // 返回包含映射中项的集合 states = capitals.keySet(); Iterator itr = states.iterator(); while (itr.hasNext()) { str = (String) itr.next(); System.out.println("国家:" + str + " ,首都: " + capitals.getProperty(str) + "."); } System.out.println(); // 查找列表,如果没有则显示为“没发现” str = capitals.getProperty("美国", "没有发现"); System.out.println("美国的首都:" + str + "."); } } ./ch16/���渚�16-15/浠g��16-15.java import java.io.* ; import java.util.* ; public class PropertiesFile { public static void main(String[] args) { Properties settings = new Properties(); try { settings.load(new FileInputStream("c:\\count.txt")); } catch (Exception e) { settings.setProperty("count", new Integer(0).toString()); } int c = Integer.parseInt(settings.getProperty("count")) + 1; System.out.println("这是本程序第" + c + "次被使用"); settings.put("count", new Integer(c).toString()); try { settings.store(new FileOutputStream("c:\\count.txt"), "PropertiesFile use it ."); } catch (Exception e) { System.out.println(e.getMessage()); } } } ./ch16/���渚�16-2/浠g��16-2.java import java.util.*; public class ArrayListToArray { public static void main(String args[]) { // 创建一ArrayList对象al ArrayList al = new ArrayList(); // 向ArrayList中加入对象 al.add(new Integer(1)); al.add(new Integer(2)); al.add(new Integer(3)); al.add(new Integer(4)); System.out.println("ArrayList 中的内容 : " + al); // 得到对象数组 Object ia[] = al.toArray(); int sum = 0; // 计算数组内容 for (int i = 0; i < ia.length; i++) sum += ((Integer) ia[i]).intValue(); System.out.println("数组累加结果是: " + sum); } } ./ch16/���渚�16-3/浠g��16-3.java import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // 创建LinkedList对象 LinkedList ll = new LinkedList(); // 加入元素到LinkedList中 ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); // 在链表的最后一个位置加上数据 ll.addLast("Z"); // 在链表的第一个位置上加入数据 ll.addFirst("A"); // 在链表第二个元素的位置上加入数据 ll.add(1, "A2"); System.out.println("ll 最初的内容:" + ll); // 从linkedlist中移除元素 ll.remove("F"); ll.remove(2); System.out.println("从ll中移除内容之后:" + ll); // 移除第一个和最后一个元素 ll.removeFirst(); ll.removeLast(); System.out.println("ll 移除第一个和最后一个元素之后的内容:" + ll); // 取得并设置值 Object val = ll.get(2); ll.set(2, (String) val + " Changed"); System.out.println("ll 被改变之后:" + ll); } } ./ch16/���渚�16-4/浠g��16-4.java import java.util.*; public class HashSetDemo { public static void main(String args[]) { // 创建HashSet对象 HashSet hs = new HashSet(); // 加入元素到HastSet中 hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } } ./ch16/���渚�16-5/浠g��16-5.java import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // 创建一TreeSet对象 TreeSet ts = new TreeSet(); // 加入元素到TreeSet中 ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); } } ./ch16/���渚�16-6/浠g��16-6.java import java.util.* ; public class IteratorDemo { public static void main(String args[]) { // 创建一个ArrayList数组 ArrayList al = new ArrayList(); // 加入元素到ArrayList中 al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); // 使用iterator显示a1中的内容 System.out.print("a1 中原始内容是:"); Iterator itr = al.iterator(); while (itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // 在ListIterator中修改内容 ListIterator litr = al.listIterator(); while (litr.hasNext()) { Object element = litr.next(); // 用set方法修改其内容 litr.set(element + "+"); } System.out.print("a1 被修改之后的内容:"); itr = al.iterator(); while (itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // 下面是将列表中的内容反向输出 System.out.print("将列表反向输出:"); // hasPreviours由后向前输出 while (litr.hasPrevious()) { Object element = litr.previous(); System.out.print(element + " "); } System.out.println(); } } ./ch16/���渚�16-7/浠g��16-7.java import java.util.* ; public class HashMapDemo { public static void main(String args[]) { // 创建HashMap对象 HashMap hm = new HashMap(); // 加入元素到HashMap中 hm.put("John Doe", new Double(3434.34)); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double(1378.00)); hm.put("Todd Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(-19.08)); // 返回包含映射中项的集合 Set set = hm.entrySet(); // 用Iterator得到HashMap中的内容 Iterator i = set.iterator(); // 显示元素 while (i.hasNext()) { //Map.Entry可以操作映射的输入 Map.Entry me = (Map.Entry) i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // 让John Doe中的值增加1000 double balance = ((Double) hm.get("John Doe")).doubleValue(); //用新的值替换掉旧的值 hm.put("John Doe", new Double(balance + 1000)); System.out.println("John Doe's 现在的资金:" + hm.get("John Doe")); } } ./ch16/���渚�16-8/浠g��16-8.java import java.util.* ; public class TreeMapDemo { public static void main(String args[]) { // 创建TreeMap对象 TreeMap tm = new TreeMap(); // 加入元素到TreeMap中 tm.put(new Integer(10000 - 2000), "张三"); tm.put(new Integer(10000 - 1500), "李四"); tm.put(new Integer(10000 - 2500), "王五"); tm.put(new Integer(10000 - 5000), "赵六"); Collection col = tm.values(); Iterator i = col.iterator(); System.out.println("按工资由高到低顺序输出:"); while (i.hasNext()) { System.out.println(i.next()); } } } ./ch16/���渚�16-9/浠g��16-9.java import java.util.*; class MyComp implements Comparator { public int compare(Object o1, Object o2) { String aStr, bStr; aStr = (String)o1; bStr = (String)o2; return bStr.compareTo(aStr); } } public class ComparatorDemo { public static void main(String args[]) { // 创建一个TreeSet对象 TreeSet ts = new TreeSet(new MyComp()); // 向TreeSet对象中加入内容 ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); // 得到Iterator的实例化对象 Iterator i = ts.iterator(); // 显示全部内容 while (i.hasNext()) { Object element = i.next(); System.out.print(element + " "); } } } ./ch16/璺����涓����/Xiti_16.java import java.util.TreeSet; public class Xiti_16 { public static void main(String args[]) { // 创建一TreeSet对象 TreeSet ts = new TreeSet(); // 加入元素到TreeSet中 ts.add("3"); ts.add("6"); ts.add("9"); ts.add("7"); ts.add("18"); ts.add("25"); System.out.println(ts); } } ./ch17/Meiju/org/lxh/enumdemo/demo00/Color.java package org.lxh.enumdemo.demo00; public class Color { private String name; public static final Color RED = new Color("红色"); public static final Color GREEN = new Color("绿色"); public static final Color BLUE = new Color("蓝色"); public String getName() { return name; } public void setName(String name) { this.name = name; } private Color(String name) { this.setName(name); } public static Color getInstance(int i) { if (i == 0) { return RED; } if (i == 1) { return GREEN; } if (i == 2) { return BLUE; } return null; } } ./ch17/Meiju/org/lxh/enumdemo/demo00/TestColor.java package org.lxh.enumdemo.demo00; public class TestColor { public static void main(String[] args) { Color c = Color.getInstance(0) ; System.out.println(c.getName()) ; } } ./ch17/Meiju/org/lxh/enumdemo/demo01/Color.java package org.lxh.enumdemo.demo01; import java.lang.*; import java.util.*; public enum Color { RED{ public String getColor(){ return "红色"; } }, GREEN{ public String getColor(){ return "绿色"; } }, BLUE{ public String getColor(){ return "蓝色"; } }; } ./ch17/Meiju/org/lxh/enumdemo/demo01/EnumMapDemo.java package org.lxh.enumdemo.demo01; import java.util.EnumMap; import java.util.Map; public class EnumMapDemo { public static void main(String[] args) { EnumMap<Color, String> eMap = new EnumMap<Color, String>(Color.class); eMap.put(Color.RED, "红色"); eMap.put(Color.GREEN, "绿色"); eMap.put(Color.BLUE, "蓝色"); for (Map.Entry<Color, String> me : eMap.entrySet()) { System.out.println(me.getKey() + " --> " + me.getValue()) ; } } } ./ch17/Meiju/org/lxh/enumdemo/demo01/EnumSetDemo01.java package org.lxh.enumdemo.demo01; import java.util.EnumSet; import java.util.Iterator; public class EnumSetDemo01 { public static void main(String[] args) { EnumSet<Color> eSet = EnumSet.noneOf(Color.class); // 表示将全部的内容设置到集合 Iterator<Color> iter = eSet.iterator() ; while(iter.hasNext()){ System.out.println(iter.next()); } } } ./ch17/Meiju/org/lxh/enumdemo/demo01/TestColor01.java package org.lxh.enumdemo.demo01; public class TestColor01 { public static void main(String[] args) { Color c = Color.RED ; // 得到红色 System.out.println(c) ; } } ./ch17/Meiju/org/lxh/enumdemo/demo01/TestColor03.java package org.lxh.enumdemo.demo01; public class TestColor03 { public static void main(String[] args) { switch (Color.RED) { case RED: { System.out.println("红色"); break; } case GREEN: { System.out.println("绿色"); break; } case BLUE: { System.out.println("蓝色"); break; } } } } ./ch17/Meiju/org/lxh/enumdemo/demo01/TestColor04.java package org.lxh.enumdemo.demo01; public class TestColor04 { public static void main(String[] args) { for (Color c : Color.values()) { System.out.print(c + "、"); } } } ./ch17/Meiju/org/lxh/enumdemo/demo01/TestColor05.java package org.lxh.enumdemo.demo01; public class TestColor05 { public static void main(String[] args) { for (Color c : Color.values()) { System.out.println(c.name() + " --> " + c.ordinal()); } } } ./ch17/Meiju/org/lxh/enumdemo/demo01/TestColor06.java package org.lxh.enumdemo.demo01; public class TestColor06 { public static void main(String[] args) { Color c = Color.valueOf(Color.class, "RED") ; System.out.println(c) ; } } ./ch17/Meiju/org/lxh/enumdemo/demo02/Color.java package org.lxh.enumdemo.demo02; public enum Color implements Info { // 实现接口 RED { public String getColor() { return "红色"; } }, GREEN { public String getColor() { return "绿色"; } }, BLUE { public String getColor(){ return "蓝色" ; } }; } ./ch17/Meiju/org/lxh/enumdemo/demo02/Info.java package org.lxh.enumdemo.demo02; public interface Info { public String getColor() ; } ./ch17/Meiju/org/lxh/enumdemo/demo02/TestColor.java package org.lxh.enumdemo.demo02; public class TestColor { public static void main(String[] args) { for (Color c : Color.values()) { System.out.println(c.ordinal() + " --> " + c.name() + ":" + c.getColor()); } } } ./ch17/Meiju/org/lxh/enumdemo/demo03/Color.java package org.lxh.enumdemo.demo03; public interface Color { public static final int RED = 0; public static final int GREEN = 1; public static final int BLUE = 2; } ./ch17/���渚�17-1/浠g��17-1.java public class Color { private String name; public static final Color RED = new Color("红色"); public static final Color GREEN = new Color("绿色"); public static final Color BLUE = new Color("蓝色"); public String getName() { return name; } public void setName(String name) { this.name = name; } private Color(String name) { this.setName(name); } public static Color getInstance(int i) { if (i == 0) { return RED; } if (i == 1) { return GREEN; } if (i == 2) { return BLUE; } return null; } } ./ch17/���渚�17-10/浠g��17-10.java package org.lxh.enumdemo.demo04; import java.util.EnumMap; import java.util.Map; public class EnumMapDemo { public static void main(String[] args) { EnumMap<Color, String> eMap = new EnumMap<Color, String>(Color.class); eMap.put(Color.RED, "红色"); eMap.put(Color.GREEN, "绿色"); eMap.put(Color.BLUE, "蓝色"); for (Map.Entry<Color, String> me : eMap.entrySet()) { System.out.println(me.getKey() + " --> " + me.getValue()) ; } } } ./ch17/���渚�17-11/浠g��17-11.java package org.lxh.enumdemo.demo04; import java.util.EnumSet; import java.util.Iterator; public class EnumSetDemo01 { public static void main(String[] args) { EnumSet<Color> eSet = EnumSet.allOf(Color.class); // 表示将全部的内容设置到集合 Iterator<Color> iter = eSet.iterator() ; while(iter.hasNext()){ System.out.println(iter.next()); } ./ch17/���渚�17-12/浠g��17-12.java package org.lxh.enumdemo.demo04; import java.util.EnumSet; import java.util.Iterator; public class EnumSetDemo02 { public static void main(String[] args) { EnumSet<Color> eSet = EnumSet.noneOf(Color.class); // 表示此类型的空集合 Iterator<Color> iter = eSet.iterator() ; while(iter.hasNext()){ System.out.println(iter.next()); } } } ./ch17/���渚�17-13/浠g��17-13.java package org.lxh.enumdemo.demo05; public enum Color { RED("红色"), GREEN("绿色"), BLUE("蓝色"); private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } Color(String name) { this.setName(name); } } ./ch17/���渚�17-14/浠g��17-14.java package org.lxh.enumdemo.demo06; public interface Info { public String getColor() ; } ./ch17/���渚�17-15/浠g��17-15.java package org.lxh.enumdemo.demo06; public enum Color implements Info { // 实现接口 RED { public String getColor() { return "红色"; } }, GREEN { public String getColor() { return "绿色"; } }, BLUE { public String getColor(){ return "蓝色" ; } }; } ./ch17/���渚�17-16/浠g��17-16.java package org.lxh.enumdemo.demo06; public class TestColor { public static void main(String[] args) { for (Color c : Color.values()) { System.out.println(c.ordinal() + " --> " + c.name() + ":" + c.getColor()); } } } ./ch17/���渚�17-17/浠g��17-17.java package org.lxh.enumdemo.demo06; public enum Color { RED { public String getColor() { return "红色"; } }, GREEN { public String getColor() { return "绿色"; } }, BLUE { public String getColor(){ return "蓝色" ; } }; public abstract String getColor() ; } ./ch17/���渚�17-18/浠g��17-18.java package org.lxh.enumdemo.demo06; public class TestColor { public static void main(String[] args) { for (Color c : Color.values()) { System.out.println(c.ordinal() + " --> " + c.name() + ":" + c.getColor()); } } } ./ch17/���渚�17-2/浠g��17-2.java package org.lxh.enumdemo.demo01; public class TestColor { public static void main(String[] args) { Color c = Color.getInstance(0) ; System.out.println(c.getName()) ; } } ./ch17/���渚�17-3/浠g��17-3.java package org.lxh.enumdemo.demo01; public interface Color { public static final int RED = 0; public static final int GREEN = 1; public static final int BLUE = 2; } ./ch17/���渚�17-4/浠g��17-4.java 01 package org.lxh.enumdemo.demo02; 02 public enum Color { 03 RED, GREEN, BLUE; 04 } ./ch17/���渚�17-5/浠g��17-5.java package org.lxh.enumdemo.demo03; public class TestColor01 { public static void main(String[] args) { Color c = Color.RED ; // 得到红色 System.out.println(c) ; } } ./ch17/���渚�17-6/浠g��17-6.java package org.lxh.enumdemo.demo03; public class TestColor03 { public static void main(String[] args) { switch (Color.RED) { case RED: { System.out.println("红色"); break; } case GREEN: { System.out.println("绿色"); break; } case BLUE: { System.out.println("蓝色"); break; } } } } ./ch17/���渚�17-7/浠g��17-7.java package org.lxh.enumdemo.demo03; public class TestColor04 { public static void main(String[] args) { for (Color c : Color.values()) { System.out.print(c + "、"); } } } ./ch17/���渚�17-8/浠g��17-8.java package org.lxh.enumdemo.demo03; public class TestColor05 { public static void main(String[] args) { for (Color c : Color.values()) { System.out.println(c.name() + " --> " + c.ordinal()); } } } ./ch17/���渚�17-9/浠g��17-9.java package org.lxh.enumdemo.demo03; public class TestColor06 { public static void main(String[] args) { Color c = Color.valueOf(Color.class, "RED") ; System.out.println(c) ; } } ./ch17/璺����涓����/Xiti_17.java public enum Day { MONDAY { return "星期一"; }, TUESDAY { public String getDay() { return "星期二"; } }, WEDNESDAY { return "星期三" ; }; public abstract String getDay() ; } ./ch18/璺����涓����/Xiti_18.java /** * Describes the Request-For-Enhancement(RFE) that led * to the presence of the annotated API element. */ public @interface RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date(); default "[unimplemented]"; } ./ch19/���渚�19-1/浠g��19-1.java public class ThreadDemo_1 { public static void main(String args[]) { new TestThread().run(); // 循环输出 for(int i=0;i<10;i++) { System.out.println("main 线程在运行"); } } } class TestThread { public void run() { for(int i=0;i<10;i++) { System.out.println("TestThread 在运行"); } } } ./ch19/���渚�19-10/浠g��9-10.java public class ThreadDaemon { public static void main(String args[]) { ThreadTest t = new ThreadTest() ; Thread tt = new Thread(t) ; tt.setDaemon(true) ; // 设置后台运行 tt.start(); } } class ThreadTest implements Runnable { public void run() { while(true) { System.out.println(Thread.currentThread().getName()+"is running."); } } } ./ch19/���渚�19-11/浠g��19-11.java public class ThreadJoin { public static void main(String[] args) { ThreadTest t=new ThreadTest(); Thread pp=new Thread(t); pp.start(); int i=0; for(int x=0;x<10;x++) { if(i==5) { try { pp.join(); // 强制运行完一线程后,再运行后面的线程 } catch(Exception e) // 会抛出InterruptedException { System.out.println(e.getMessage()); } } System.out.println("main Thread "+i++); } } } class ThreadTest implements Runnable { public void run() { String str=new String(); int i=0; for(int x=0;x<10;x++) { System.out.println(Thread.currentThread().getName()+" ---->> "+i++); } } } ./ch19/���渚�19-12/浠g��19-12.java public class TwoThreadSleep extends Thread { public void run() { loop(); } public void loop() { String name = Thread.currentThread().getName(); System.out.println(name+" ---->> 刚进入loop方法"); for ( int i = 0; i < 10; i++ ) { try { Thread.sleep(2000); } catch ( InterruptedException x ) {} System.out.println("name=" + name); } System.out.println(name+" ---->> 离开loop方法") ; } public static void main(String[] args) { TwoThreadSleep tt = new TwoThreadSleep(); tt.setName("my worker thread"); tt.start(); try { Thread.sleep(700); } catch ( InterruptedException x ) {} tt.loop(); } } ./ch19/���渚�19-13/浠g��19-13.java public class SleepInterrupt implements Runnable { public void run() { try { System.out.println("在run()方法中 - 这个线程休眠20秒"); Thread.sleep(20000); System.out.println("在run()方法中 - 继续运行"); } catch (InterruptedException x) { System.out.println("在run()方法中 - 中断线程"); return; } System.out.println("在run()方法中 - 休眠之后继续完成"); System.out.println("在run()方法中 - 正常退出"); } public static void main(String[] args) { SleepInterrupt si = new SleepInterrupt(); Thread t = new Thread(si); t.start(); // 在此休眠是为确保线程能运行一会 try { Thread.sleep(2000); } catch (InterruptedException x) {} System.out.println("在main()方法中 - 中断其它线程"); t.interrupt(); System.out.println("在main()方法中 - 退出"); } } ./ch19/���渚�19-14/浠g��19-14.java public class InterruptCheck { public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("A:t.isInterrupted() = " + t.isInterrupted()); t.interrupt(); System.out.println("B:t.isInterrupted() = " + t.isInterrupted()); System.out.println("C:t.isInterrupted() = " + t.isInterrupted()); try { Thread.sleep(2000); System.out.println("线程没有被中断!"); } catch ( InterruptedException x ) { System.out.println("线程被中断!"); } // 因为sleep抛出了异常,所以它清除了中断标志 System.out.println("D:t.isInterrupted() = " + t.isInterrupted()); } } ./ch19/���渚�19-15/浠g��19-15.java public class ThreadDemo_5 { public static void main(String [] args) { TestThread t = new TestThread() ; // 启动了四个线程,实现了资源共享的目的 new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); } } class TestThread implements Runnable { private int tickets=20; public void run() { while(true) { if(tickets>0) { try{ Thread.sleep(100); } catch(Exception e){} System.out.println(Thread.currentThread().getName() +"出售票"+tickets--); } } } } ./ch19/���渚�19-16/浠g��19-16.java class A { synchronized void funA(B b) { String name=Thread.currentThread().getName(); System.out.println(name+ " 进入 A.foo "); try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println(name+ " 调用 B类中的last()方法"); b.last(); } synchronized void last() { System.out.println("A类中的last()方法"); } } class B { synchronized void funB(A a) { String name=Thread.currentThread().getName(); System.out.println(name + " 进入 B 类中的"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println(name + " 调用 A类中的last()方法"); a.last(); } synchronized void last() { System.out.println("B类中的last()方法"); } } class DeadLockDemo implements Runnable { A a=new A(); B b=new B(); DeadLockDemo() { // 设置当前线程的名称 Thread.currentThread().setName("Main -->> Thread"); new Thread(this).start(); a.funA(b); System.out.println("main线程运行完毕"); } public void run() { Thread.currentThread().setName("Test -->> Thread"); b.funB(a); System.out.println("其他线程运行完毕"); } public static void main(String[] args) { new DeadLockDemo(); } } ./ch19/���渚�19-17/浠g��19-17.java class Producer implements Runnable { P q=null; public Producer(P q) { this.q=q; } public void run() { int i=0; while(true) { if(i==0) { q.name="张三"; q.sex="男"; } else { q.name="李四"; q.sex="女"; } i=(i+1)%2; } } } class P { String name="李四"; String sex="女"; } class Consumer implements Runnable { P q=null; public Consumer(P q) { this.q=q; } public void run() { while(true) { System.out.println(q.name + " ---->" + q.sex); } } } public class ThreadCommunation { public static void main(String [] args) { P q=new P(); new Thread(new Producer(q)).start(); new Thread(new Consumer(q)).start(); } } ./ch19/���渚�19-18/浠g��19-18.java class Producer implements Runnable { P q=null; public Producer(P q) { this.q=q; } public void run() { int i=0; while(true) { if(i==0) { q.set("张三","男"); } else { q.set("李四","女"); } i=(i+1)%2; } } } class P { private String name="李四"; private String sex="女"; public synchronized void set(String name,String sex) { this.name = name ; this.sex =sex ; } public synchronized void get() { System.out.println(this.name + " ---->" + this.sex ) ; } } class Consumer implements Runnable { P q=null; public Consumer(P q) { this.q=q; } public void run() { while(true) { q.get(); } } } public class ThreadCommunation { public static void main(String [] args) { P q=new P(); new Thread(new Producer(q)).start(); new Thread(new Consumer(q)).start(); } } ./ch19/���渚�19-19/浠g��19-19.java class P { private String name="李四"; private String sex="女"; boolean bFull = false ; public synchronized void set(String name,String sex) { if(bFull) { try { wait() ; // 后来的线程要等待 } catch(InterruptedException e) {} } this.name = name ; try { Thread.sleep(10); } catch(Exception e) { System.out.println(e.getMessage()); } this.sex = sex ; bFull = true ; notify(); // 唤醒最先到达的线程 } public synchronized void get() { if(!bFull) { try { wait() ; } catch(InterruptedException e) {} } System.out.println(name+" ---->"+sex); bFull = false ; notify(); } } ./ch19/���渚�19-2/浠g��19-2.java public class ThreadDemo_1 { public static void main(String args[]) { new TestThread().start(); // 循环输出 for(int i=0;i<10;i++) { System.out.println("main 线程在运行"); } } } class TestThread extends Thread { public void run() { for(int i=0;i<10;i++) { System.out.println("TestThread 在运行"); } } } ./ch19/���渚�19-20/浠g��19-20.java public class ThreadLife { public static void main(String [] args) { TestThread t=new TestThread(); new Thread(t).start(); for(int i=0;i<10; i++) { if(i == 5) t.stopMe(); System.out.println("Main 线程在运行"); } } } class TestThread implements Runnable { private boolean bFlag = true; public void stopMe() { bFlag = false; } public void run() { while(bFlag) { System.out.println(Thread.currentThread().getName()+" 在运行"); } } } ./ch19/���渚�19-3/浠g��19-3.java public class ThreadDemo_2 { public static void main(String args[]) { TestThread t = new TestThread() ; new Thread(t).start(); // 循环输出 for(int i=0;i<10;i++) { System.out.println("main 线程在运行"); } } } class TestThread implements Runnable { public void run() { for(int i=0;i<10;i++) { System.out.println("TestThread 在运行"); } } } ./ch19/���渚�19-4/浠g��19-4.java public class ThreadDemo_3 { public static void main(String [] args) { TestThread t=new TestThread(); // 一个线程对象只能启动一次 t.start(); t.start(); t.start(); t.start(); } } class TestThread extends Thread { private int tickets=20; public void run() { while(true) { if(tickets>0) System.out.println(Thread.currentThread().getName()+"出售票"+tickets--); } } } ./ch19/���渚�19-5/浠g��19-5.java public class ThreadDemo_3 { public static void main(String [] args) { // 启动了四个线程,分别执行各自的操作 new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); } } class TestThread extends Thread { private int tickets=20; public void run() { while(true) { if(tickets>0) System.out.println(Thread.currentThread().getName() +"出售票"+tickets--); } } } ./ch19/���渚�19-6/浠g��19-6.java public class ThreadDemo_4 { public static void main(String [] args) { TestThread t = new TestThread() ; // 启动了四个线程,并实现了资源共享的目的 new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); new Thread(t).start(); } } class TestThread implements Runnable { private int tickets=20; public void run() { while(true) { if(tickets>0) System.out.println(Thread.currentThread().getName()+"出售票"+tickets--); } } } ./ch19/���渚�19-7/浠g��19-7.java public class GetNameThreadDemo extends Thread { public void run() { for(int i=0;i<10;i++) printMsg(); } public void printMsg() { // 获得运行此代码的线程的引用 Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name = "+name); } public static void main(String[] args) { GetNameThreadDemo t1 = new GetNameThreadDemo(); t1.start(); for(int i=0;i<10;i++) { t1.printMsg(); } } } ./ch19/���渚�19-8/浠g��19-8.java public class SetNameThreadDemo extends Thread { public void run() { for(int i=0;i<10;i++) { printMsg(); } } public void printMsg() { // 获得运行此代码的线程的引用 Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name = "+name); } public static void main(String args[]) { SetNameThreadDemo tt = new SetNameThreadDemo(); // 在这里设置线程的名称 tt.setName("test thread"); tt.start(); for(int i=0;i<10;i++) { tt.printMsg(); } } } ./ch19/���渚�19-9/浠g��19-9.java public class StartThreadDemo extends Thread { public void run() { for(int i=0;i<10;i++) { printMsg(); } } public void printMsg() { // 获得运行此代码的线程的引用 Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name = "+name); } public static void main(String[] args) { StartThreadDemo t = new StartThreadDemo(); t.setName("test Thread"); System.out.println("调用start()方法之前 , t.isAlive() = "+t.isAlive()); t.start(); System.out.println("刚调用start()方法时 , t.isAlive() = "+t.isAlive()); for(int i=0;i<10;i++) { t.printMsg(); } // 下面于句的数出结果是不固定的,有时输出false,有时输出true System.out.println("main()方法结束时 , t.isAlive() = "+t.isAlive()); } } ./ch19/璺����涓����/Xiti_19.java public class Xiti_19 implements Runnable { public void run() { try { System.out.println("在run()方法中 - 这个线程休眠10秒"); Thread.sleep(10000); System.out.println("在run()方法中 - 继续运行"); } catch (InterruptedException x) { System.out.println("在run()方法中 - 中断线程"); return; } System.out.println("在run()方法中 - 休眠之后继续完成"); System.out.println("在run()方法中 - 正常退出"); } public static void main(String[] args) { Xiti_19 si = new Xiti_19(); Thread t = new Thread(si); t.start(); try { Thread.sleep(1000); } catch (InterruptedException x) {} System.out.println("在main()方法中 - 中断其它线程"); t.interrupt(); System.out.println("在main()方法中 - 退出"); } } ./ch20/���渚�20-1/浠g��20-1.java import java.io.*; public class FileDemo { public static void main(String[] args) { File f=new File("c:\\1.txt"); if(f.exists()) f.delete(); else try { f.createNewFile(); } catch(Exception e) { System.out.println(e.getMessage()); } // getName()方法,取得文件名 System.out.println("文件名:"+f.getName()); // getPath()方法,取得文件路径 System.out.println("文件路径:"+f.getPath()); // getAbsolutePath()方法,得到绝对路径名 System.out.println("绝对路径:"+f.getAbsolutePath()); // getParent()方法,得到父文件夹名 System.out.println("父文件夹名称:"+f.getParent()); // exists(),判断文件是否存在 System.out.println(f.exists()?"文件存在":"文件不存在"); // canWrite(),判断文件是否可写 System.out.println(f.canWrite()?"文件可写":"文件不可写"); // canRead(),判断文件是否可读 System.out.println(f.canRead()?"文件可读":"文件不可读"); /// isDirectory(),判断是否是目录 System.out.println(f.isDirectory()?"是":"不是"+"目录"); // isFile(),判断是否是文件 System.out.println(f.isFile()?"是文件":"不是文件"); // isAbsolute(),是否是绝对路径名称 System.out.println(f.isAbsolute()?"是绝对路径":"不是绝对路径"); // lastModified(),文件最后的修改时间 System.out.println("文件最后修改时间:"+f.lastModified()); // length(),文件的长度 System.out.println("文件大小:"+f.length()+" Bytes"); } } ./ch20/���渚�20-10/浠g��20-10.java import java.io.*; public class SequenceDemo { public static void main(String[] args) throws IOException { // 声明两个文件读入流 FileInputStream in1 = null, in2 = null; // 声明一个序列流 SequenceInputStream s = null; FileOutputStream out = null; try { // 构造两个被读入的文件 File inputFile1 = new File("c:\\1.txt"); File inputFile2 = new File("c:\\2.txt"); // 构造一个输出文件 File outputFile = new File("c:\\12.txt"); in1 = new FileInputStream(inputFile1); in2 = new FileInputStream(inputFile2); // 将两输入流合为一个输入流 s = new SequenceInputStream(in1, in2); out = new FileOutputStream(outputFile); int c; while ((c = s.read()) != -1) out.write(c); in1.close(); in2.close(); s.close(); out.close(); System.out.println("ok..."); } catch (IOException e) { e.printStackTrace(); } finally { if (in1 != null) try { in1.close(); } catch (IOException e) { } if (in2 != null) try { in2.close(); } catch (IOException e) { } if (s != null) try { s.close(); } catch (IOException e) { } if (out != null) try { out.close(); } catch (IOException e) { } } } } ./ch20/���渚�20-11/浠g��20-11.java import java.io.*; public class BufferDemo { public static void main(String args[]) { BufferedReader buf = null; buf = new BufferedReader(new InputStreamReader(System.in)); String str = null; while (true) { System.out.print("请输入数字:"); try { str = buf.readLine(); } catch (IOException e) { e.printStackTrace(); } int i = -1; try { i = Integer.parseInt(str); i++; System.out.println("输入的数字修改后为:" + i); break; } catch (Exception e) { System.out.println("输入的内容不正确,请重新输入!"); } } } } ./ch20/���渚�20-12/浠g��20-12.java import java.io.* ; public class EncodingDemo { public static void main(String args[]) throws Exception { // 在这里将字符串通过getBytes()方法,编码成GB2312 byte b[] = "大家一起来学Java语言".getBytes("GB2312") ; OutputStream out = new FileOutputStream(new File("c:\\encoding.txt")) ; out.write(b) ; out.close() ; } } ./ch20/���渚�20-13/浠g��20-13.java public class SetDemo { public static void main(String args[]) { System.getProperties().put("file.encoding","GB2312") ; } } ./ch20/���渚�20-14/浠g��20-14.java import java.io.* ; public class EncodingDemo { public static void main(String args[]) throws Exception { // 在这里将字符串通过getBytes()方法,编码成ISO8859-1 byte b[] = "大家一起来学Java语言".getBytes("ISO8859-1") ; OutputStream out = new FileOutputStream(new File("c:\\encoding.txt")) ; out.write(b) ; out.close() ; } } ./ch20/���渚�20-15/浠g��20-15.java public class GetDemo { public static void main(String args[]) { // 输出全部环境变量 System.getProperties().list(System.out); } } ./ch20/���渚�20-16/浠g��20-16.java import java.io.* ; public class Person implements Serializable { private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } public String toString() { return " 姓名:"+this.name+",年龄:"+this.age ; } }; ./ch20/���渚�20-17/浠g��20-17.java import java.io.*; public class SerializableDemo { public static void main( String args[] ) throws Exception { File f = new File("SerializedPerson") ; serialize(f); deserialize(f); } // 以下方法为序列化对象方法 public static void serialize(File f) throws Exception { OutputStream outputFile = new FileOutputStream(f); ObjectOutputStream cout = new ObjectOutputStream(outputFile); cout.writeObject(new Person("张三",25)); cout.close(); } // 以下方法为反序列化对象方法 public static void deserialize(File f) throws Exception { InputStream inputFile = new FileInputStream(f); ObjectInputStream cin = new ObjectInputStream(inputFile); Person p = (Person) cin.readObject(); System.out.println(p); } } ./ch20/���渚�20-2/浠g��20-2.java import java.io.*; public class RandomFileDemo { public static void main(String [] args) throws Exception { Employee e1 = new Employee("zhangsan",23); Employee e2 = new Employee("lisi",24); Employee e3 = new Employee("wangwu",25); RandomAccessFile ra=new RandomAccessFile("c:\\employee.txt","rw"); ra.write(e1.name.getBytes()); ra.writeInt(e1.age); ra.write(e2.name.getBytes()); ra.writeInt(e2.age); ra.write(e3.name.getBytes()); ra.writeInt(e3.age); ra.close(); RandomAccessFile raf=new RandomAccessFile("c:\\employee.txt","r"); int len=8; raf.skipBytes(12); // 跳过第一个员工的信息,其姓名8字节,年龄4字节 System.out.println("第二个员工信息:"); String str=""; for(int i=0;i<len;i++) str=str+(char)raf.readByte(); System.out.println("name:"+str); System.out.println("age:"+raf.readInt()); System.out.println("第一个员工的信息:"); raf.seek(0); // 将文件指针移动到文件开始位置 str=""; for(int i=0;i<len;i++) str=str+(char)raf.readByte(); System.out.println("name:"+str); System.out.println("age:"+raf.readInt()); System.out.println("第三个员工的信息:"); raf.skipBytes(12); // 跳过第二个员工信息 str="" ; for(int i=0;i<len;i++) str=str+(char)raf.readByte(); System.out.println("name:"+str.trim()); System.out.println("age:"+raf.readInt()); raf.close(); } } class Employee { String name; int age; final static int LEN=8; public Employee(String name,int age) { if(name.length()>LEN) { name=name.substring(0,8); } else { while(name.length()<LEN) name=name+"\u0000"; } this.name=name; this.age=age; } } ./ch20/���渚�20-3/浠g��20-3.java import java.io.*; public class StreamDemo { public static void main(String args[]) { File f = new File("c:\\temp.txt") ; OutputStream out = null ; try { out = new FileOutputStream(f) ; } catch (FileNotFoundException e) { e.printStackTrace(); } // 将字符串转成字节数组 byte b[] = "Hello World!!!".getBytes() ; try { // 将byte数组写入到文件之中 out.write(b) ; } catch (IOException e1) { e1.printStackTrace(); } try { out.close() ; } catch (IOException e2) { e2.printStackTrace(); } // 以下为读文件操作 InputStream in = null ; try { in = new FileInputStream(f) ; } catch (FileNotFoundException e3) { e3.printStackTrace(); } // 开辟一个空间用于接收文件读进来的数据 byte b1[] = new byte[1024] ; int i = 0 ; try { // 将b1的引用传递到read()方法之中,同时此方法返回读入数据的个数 i = in.read(b1) ; } catch (IOException e4) { e4.printStackTrace(); } try { in.close() ; } catch (IOException e5) { e5.printStackTrace(); } //将byte数组转换为字符串输出 System.out.println(new String(b1,0,i)) ; } } ./ch20/���渚�20-4/浠g��20-4.java import java.io.*; public class CharDemo { public static void main(String args[]) { File f = new File("c:\\temp.txt") ; Writer out = null ; try { out = new FileWriter(f) ; } catch (IOException e) { e.printStackTrace(); } // 声明一个String类型对象 String str = "Hello World!!!" ; try { // 将str内容写入到文件之中 out.write(str) ; } catch (IOException e1) { e1.printStackTrace(); } try { out.close() ; } catch (IOException e2) { e2.printStackTrace(); } // 以下为读文件操作 Reader in = null ; try { in = new FileReader(f) ; } catch (FileNotFoundException e3) { e3.printStackTrace(); } // 开辟一个空间用于接收文件读进来的数据 char c1[] = new char[1024] ; int i = 0 ; try { // 将c1的引用传递到read()方法之中,同时此方法返回读入数据的个数 i = in.read(c1) ; } catch (IOException e4) { e4.printStackTrace(); } try { in.close() ; } catch (IOException e5) { e5.printStackTrace(); } //将字符数组转换为字符串输出 System.out.println(new String(c1,0,i)) ; } } ./ch20/���渚�20-5/浠g��20-5.java import java.io.*; public class PipeStreamDemo { public static void main(String args[]) { try { Sender sender = new Sender(); // 产生两个线程对象 Receiver receiver = new Receiver(); PipedOutputStream out = sender.getOutputStream(); // 写入 PipedInputStream in = receiver.getInputStream(); // 读出 out.connect(in); // 将输出发送到输入 sender.start(); // 启动线程 receiver.start(); } catch(IOException e) { System.out.println(e.getMessage()); } } } class Sender extends Thread { private PipedOutputStream out=new PipedOutputStream(); public PipedOutputStream getOutputStream() { return out; } public void run() { String s=new String("Receiver,你好!"); try { out.write(s.getBytes()); // 写入(发送) out.close(); } catch(IOException e) { System.out.println(e.getMessage()); } } } class Receiver extends Thread { private PipedInputStream in=new PipedInputStream(); public PipedInputStream getInputStream() { return in; } public void run() { String s=null; byte [] buf = new byte[1024]; try { int len =in.read(buf); // 读出数据 s = new String(buf,0,len); System.out.println("收到了以下信息:"+s); in.close(); } catch(IOException e) { System.out.println(e.getMessage()); } } } ./ch20/���渚�20-6/浠g��20-6.java import java.io.* ; public class ByteArrayDemo { public static void main(String[] args) throws Exception { String tmp = "abcdefghijklmnopqrstuvwxyz"; byte[] src = tmp.getBytes(); // src为转换前的内存块 ByteArrayInputStream input = new ByteArrayInputStream(src); ByteArrayOutputStream output = new ByteArrayOutputStream(); new ByteArrayDemo().transform(input, output); byte[] result = output.toByteArray(); // result为转换后的内存块 System.out.println(new String(result)); } public void transform(InputStream in, OutputStream out) { int c = 0; try { while ((c = in.read()) != -1) // read在读到流的结尾处返回-1 { int C = (int) Character.toUpperCase((char) c); out.write(C); } } catch (Exception e) { e.printStackTrace(); } } } ./ch20/���渚�20-7/浠g��20-7.java import java.io.*; public class SystemPrintDemo { public static void main(String args[]) { PrintWriter out = null; // 通过System.out为PrintWriter实例化 out = new PrintWriter(System.out); // 向屏幕上输出 out. print ("Hello World!"); out.close(); } } ./ch20/���渚�20-8/浠g��20-8.java import java.io.*; public class FilePrint { public static void main(String args[]) { PrintWriter out = null ; File f = new File("c:\\temp.txt") ; try { out = new PrintWriter(new FileWriter(f)) ; } catch (IOException e) { e.printStackTrace(); } // 由FileWriter实例化,则向文件中输出 out. print ("Hello World!"+"\r\n"); out.close() ; } } ./ch20/���渚�20-9/浠g��20-9.java import java.io.* ; public class DataStreamDemo { public static void main(String[] args) throws IOException { // 将数据写入某一种载体 DataOutputStream out = new DataOutputStream( w FileOutputStream("order.txt")); // 价格 double[] prices = { 18.99, 9.22, 14.22, 5.22, 4.21 }; // 数目 int[] units = { 10, 10, 20, 39, 40 }; // 产品名称 String[] descs = { "T恤杉", "杯子", "洋娃娃", "大头针", "钥匙链" }; // 向数据过滤流写入主要类型 for (int i = 0; i < prices.length; i++) { // 写入价格,使用tab隔开数据 out.writeDouble(prices[i]); out.writeChar('\t'); // 写入数目 out.writeInt(units[i]); out.writeChar('\t'); // 写入产品名称,行尾加入换行符 out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); // 将数据读出 DataInputStream in = new DataInputStream( w FileInputStream("order.txt")); double price; int unit; StringBuffer desc; double total = 0.0; try { // 当文本被全部读出以后会抛出EOFException异常,中断循环 while (true) { // 读出价格 price = in.readDouble(); // 跳过tab in.readChar(); // 读出数目 unit = in.readInt(); // 跳过tab in.readChar(); char chr; // 读出产品名称 desc = new StringBuffer(); while ((chr = in.readChar()) != '\n') { desc.append(chr); } System.out.println("定单信息: " + "产品名称:"+desc +",\t数量:+unit+",\t价格:"+price); total = total + unit * price; } } catch (EOFException e) { System.out.println("\n总共需要:" + total+"元"); } in.close(); } } ./ch20/璺����涓����/Xiti_20.java import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class Xiti_20 { public static void main(String args[]) { File f = new File("c:\\Xiti_16.txt") ; Writer out = null ; try { out = new FileWriter(f) ; } catch (IOException e) { e.printStackTrace(); } String str = "Here is my file." ; try { out.write(str) ; } catch (IOException e1) { e1.printStackTrace(); } try { out.close() ; } catch (IOException e2) { e2.printStackTrace(); } Reader in = null ; try { in = new FileReader(f) ; } catch (FileNotFoundException e3) { e3.printStackTrace(); } char c1[] = new char[1024] ; int i = 0 ; try { i = in.read(c1) ; } catch (IOException e4) { e4.printStackTrace(); } try { in.close() ; } catch (IOException e5) { e5.printStackTrace(); } System.out.println(new String(c1,0,i)) ; } } ./ch21/AcceptParam/src/test/AcceptParam.java package test ; import java.awt.Graphics; import java.applet.Applet; public class AcceptParam extends Applet { String tempString,score; public void init() { // 得到web页中的str参数的值 tempString = getParameter("str"); if(tempString.equals("及格")) // 如果字符串等于"及格" score = "60-70"; else if(tempString.equals("中")) // 如果字符串等于"中" score = "70-80"; else if(tempString.equals("良")) // 如果字符串等于"良" score = "80-90"; else if(tempString.equals("优")) // 如果字符串等于"优" score = "90-100"; else score = "0-60" ; } public void paint(Graphics g) { g.drawString(score,10,25); // 输出分数段 } } ./ch21/HelloApplet/src/test/HelloApplet.java package test ; import java.awt.Graphics; import java.applet.Applet; public class HelloApplet extends Applet { public void paint(Graphics g) { g.drawString("这是我的Java Applet程序!",5,30); // 输出字符串 } } ./ch21/HelloAppletDemo/src/test/HelloAppletDemo.java package test ; import java.awt.Graphics; import java.applet.Applet; public class HelloAppletDemo extends Applet { String mystring=""; public void paint(Graphics g) { g.drawString(mystring,5,30); // 输出字符串 } public void init() { mystring=mystring+"正在初始化……"; repaint(); } public void start() { mystring=mystring+"正在开始执行程序……"; repaint(); } public void stop() { mystring=mystring+"正在停止执行程序……"; repaint(); } public void destory() { mystring=mystring+"正在收回资源……"; repaint(); } } ./ch21/璺����涓����/Xiti_21/src/test/Xiti_21.java package test ; import java.awt.Graphics; import java.applet.Applet; public class Xiti_21 extends Applet { public void paint(Graphics g) { g.drawString("这是我的Java Applet程序!",5,30); // 输出字符串 } } ./ch22/���渚�22-1/浠g��22-1.java import java.io.*; import java.net.*; public class HelloServer { public static void main(String[] args) throws IOException { ServerSocket serversocket=null; PrintWriter out=null; try { // 在下面实例化了一个服务器端的Socket连接 serversocket=new ServerSocket(9999); } catch(IOException e) { System.err.println("Could not listen on port:9999."); System.exit(1); } Socket clientsocket=null; try { // accept()方法用来监听客户端的连接 clientsocket=serversocket.accept(); } catch(IOException e) { System.err.println("Accept failed."); System.exit(1); } out=new PrintWriter(clientsocket.getOutputStream(),true); out.println("hello world!"); clientsocket.close(); serversocket.close(); } } ./ch22/���渚�22-2/浠g��22-2.java import java.io.*; import java.net.*; public class HelloClient { public static void main(String[] args) throws IOException { Socket hellosocket=null; BufferedReader in=null; // 下面这段程序,用来将输入输出流与socket关联 try { hellosocket=new Socket("localhost",9999); in=new BufferedReader( tStreamReader(hellosocket.getInputStream())); } catch(UnknownHostException e) { System.err.println("Don't know about host:localhost!"); System.exit(1); } catch(IOException e) { System.err.println("Couldn't get I/O for the connection."); System.exit(1); } System.out.println(in.readLine()); in.close(); hellosocket.close(); } } ./ch22/���渚�22-3/浠g��22-3.java import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; PrintWriter out = null; BufferedReader in = null; try { // 实例化监听端口 serverSocket = new ServerSocket(1111); } catch (IOException e) { System.err.println("Could not listen on port: 1111."); System.exit(1); } Socket incoming = null; while(true) { incoming = serverSocket.accept(); out = new PrintWriter(incoming.getOutputStream(), true); // 将字节流放入字符流缓冲之中 in = new BufferedReader( new InputStreamReader(incoming.getInputStream())); // 提示信息 out.println("Hello! . . . "); out.println("Enter BYE to exit"); out.flush(); // 在没有异常的情况下不断循环 while(true) { // 只有当有用户输入数据的时候才返回数据内容 String str = in.readLine(); // 当用户连接断掉时会返回空值null if(str == null) { // 退出循环 break; } else { // 对用户输入字串加前缀Echo:,将此信息打印到客户端 out.println("Echo: "+str); out.flush(); // 退出命令,equalsIgnoreCase()是不区分大小写的比较 if(str.trim().equalsIgnoreCase("BYE")) break; } } // 收尾工作 out.close(); in.close(); incoming.close(); serverSocket.close(); } } } ./ch22/���渚�22-4/浠g��22-4.java import java.io.*; import java.net.*; // 客户端程序 public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket ( "localhost", 1111); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } System.out.println(in.readLine()); System.out.println(in.readLine()); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; // 将客户端Socket输入流输出到标准输出 while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println(in.readLine()); } out.close(); in.close(); echoSocket.close(); } } ./ch22/���渚�22-5/浠g��22-5.java import java.net.*; import java.io.*; public class EchoMultiServerThread extends Thread { private Socket socket = null; public EchoMultiServerThread(Socket socket) { super("EchoMultiServerThread"); // 声明一个socket对象 this.socket = socket; } public void run() { try { PrintWriter out = null; BufferedReader in = null; out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(socket.getInputStream())); out.println("Hello! . . . "); out.println("Enter BYE to exit"); out.flush(); while(true) { String str = in.readLine(); if(str == null) { break; } else { out.println("Echo: "+str); out.flush(); if(str.trim().equalsIgnoreCase("BYE")) break; } } out.close(); in.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } ./ch22/���渚�22-6/浠g��22-6.java import java.io.*; import java.net.*; // 多线程的服务器端程序 public class EchoServerThread { public static void main(String[] args) throws IOException { // 声明一个serverSocket ServerSocket serverSocket = null; // 声明一个监听标识 boolean listening = true; try { serverSocket = new ServerSocket(1111); } catch (IOException e) { System.err.println("Could not listen on port: 1111."); System.exit(1); } // 如果处于监听状态则开启一个线程 while(listening) { // 实例化一个服务端的socket与请求socket建立连接 new EchoMultiServerThread(serverSocket.accept()).start(); } // 将serverSocket的关闭操作放在循环外, // 只有当监听状态为false时,服务才关闭 serverSocket.close(); } } ./ch22/���渚�22-7/浠g��22-7.java import java.net.*; import java.io.*; public class UdpReceive { public static void main(String[] args) { DatagramSocket ds = null; byte[] buf = new byte[1024]; DatagramPacket dp = null; try { ds = new DatagramSocket(9000); } catch (SocketException ex) { } // 创建DatagramPacket时,要求的数据格式是byte型数组 dp = new DatagramPacket(buf, 1024); try { ds.receive(dp); } catch (IOException ex1) { } /* * 调用public String(byte[] bytes,int offset,int length)构造方法, * 将byte型的数组转换成字符串 */ String str = new String(dp.getData(), 0, dp.getLength()) + " from " + dp.getAddress().getHostAddress() + " : " + dp.getPort(); System.out.println(str); ds.close(); } } ./ch22/���渚�22-8/浠g��22-8.java import java.net.*; import java.io.*; public class UdpSend { public static void main(String[] args) { // 要编写UDP网络程序,首先要用到java.net.DatagramSocket类 DatagramSocket ds = null; DatagramPacket dp = null; try { ds = new DatagramSocket(3000); } catch (SocketException ex) { } String str = "hello world "; try { dp = new DatagramPacket(str.getBytes(), str.length(), InetAddress .getByName("localhost"), 9000); // 调用getByName()方法可以返回一个InetAddress类的实例对象 } catch (UnknownHostException ex1) { } try { ds.send(dp); } catch (IOException ex2) { } ds.close(); } } ./ch22/璺����涓����/Xiti_22/src/Xiti_22_client.java import java.io.*; import java.net.*; // 客户端程序 public class Xiti_22_client { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket ( "localhost", 1111); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: localhost."); System.exit(1); } System.out.println(in.readLine()); System.out.println(in.readLine()); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println(in.readLine()); } out.close(); in.close(); echoSocket.close(); } } ./ch22/璺����涓����/Xiti_22/src/Xiti_22_server.java import java.io.*; // 服务器端 import java.net.*; public class Xiti_22_server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; PrintWriter out = null; BufferedReader in = null; try { serverSocket = new ServerSocket(1111); } catch (IOException e) { System.err.println("Could not listen on port: 1111."); System.exit(1); } Socket incoming = null; while(true) { incoming = serverSocket.accept(); out = new PrintWriter(incoming.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(incoming.getInputStream())); out.println("Hello! . . . "); out.println("Enter BYE to exit"); out.flush(); while(true) { String str = in.readLine(); if(str == null) { break; } else { out.println("客户器端: "+str); out.flush(); if(str.trim().equalsIgnoreCase("BYE")) break; } } out.close(); in.close(); incoming.close(); serverSocket.close(); } } } ./ch23/JDBCproject1.0/wf/network/execdemo01/InputData.java package wf.network.execdemo01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class InputData { private BufferedReader buf = null; public InputData() { this.buf = new BufferedReader(new InputStreamReader(System.in)); } public String getString(String info) { String str = null; System.out.print(info);// 打印提示信息 try { str = this.buf.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int getInt(String info, String err) { int temp = 0; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\d+")) { temp = Integer.parseInt(str); flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } public float getFloat(String info, String err) { float temp = 0.0f; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\d+.?\\d+")) { temp = Float.parseFloat(str); flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } public char getChar(String info, String err) { char temp = ' '; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\w")) { temp = str.charAt(0); flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } public Date getDate(String info, String err) { Date temp = null ; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\d{4}-\\d{2}-\\d{2}")) { try { temp = new SimpleDateFormat("yyyy-MM-dd").parse(str) ; } catch (ParseException e) { System.out.print(err) ; } flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } } ./ch23/JDBCproject1.0/wf/network/execdemo01/InsertDemo.java package wf.network.execdemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class InsertDemo { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null; // 表示数据库的更新操作 InputData input = new InputData() ; String name = input.getString("请输入姓名:"); int age = input.getInt("请输入年龄:", "年龄必须是数字,"); String date = input.getString("请输入生日:"); float salary = input.getFloat("请输入工资:", "输入的工资必须是数字,"); String sql = "INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'" + name + "'," + age + ",TO_DATE('" + date + "','yyyy-mm-dd')," + salary + ") "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement(); // 执行SQL语句,更新数据库 stmt.executeUpdate(sql); // 4、关闭数据库 conn.close(); } } ./ch23/JDBCproject1.0/wf/network/JDBCproject01/ConnectJDBC.java package wf.network.JDBCproject01; import java.sql.Connection; import java.sql.DriverManager; public class ConnectJDBC { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); System.out.println(conn); // 4、关闭数据库 conn.close(); } } ./ch23/JDBCproject1.0/wf/network/prepareddemo01/BatchInsertDemo.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class BatchInsertDemo { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null; // 表示数据库的更新操作 String sql = "INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,?,?,?,?) "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ;// 使用预处理的方式创建对象 for(int i=0;i<10;i++){ pstmt.setString(1, "lxh-" + i);// 第一个?号的内容 pstmt.setInt(2, 20 + i); // 第二个?号的内容 pstmt.setDate(3, new java.sql.Date(new java.util.Date().getTime())); pstmt.setFloat(4, 900*i); pstmt.addBatch() ; // 增加批处理 } // 执行SQL语句,更新数据库 int i[] = pstmt.executeBatch() ; System.out.println(i.length); // 4、关闭数据库 pstmt.close() ; conn.close(); } } ./ch23/JDBCproject1.0/wf/network/prepareddemo01/InputData.java package wf.network.prepareddemo01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class InputData { private BufferedReader buf = null; public InputData() { this.buf = new BufferedReader(new InputStreamReader(System.in)); } public String getString(String info) { String str = null; System.out.print(info);// 打印提示信息 try { str = this.buf.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int getInt(String info, String err) { int temp = 0; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\d+")) { temp = Integer.parseInt(str); flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } public float getFloat(String info, String err) { float temp = 0.0f; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\d+.?\\d+")) { temp = Float.parseFloat(str); flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } public char getChar(String info, String err) { char temp = ' '; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\w")) { temp = str.charAt(0); flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } public Date getDate(String info, String err) { Date temp = null ; boolean flag = true;// 定义一个标志位 while (flag) { String str = this.getString(info); if (str.matches("\\d{4}-\\d{2}-\\d{2}")) { try { temp = new SimpleDateFormat("yyyy-MM-dd").parse(str) ; } catch (ParseException e) { System.out.print(err) ; } flag = false;// 退出循环 } else { System.out.print(err); } } return temp; } } ./ch23/JDBCproject1.0/wf/network/prepareddemo01/InsertDemo.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Date; public class InsertDemo { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null; // 表示数据库的更新操作 InputData input = new InputData() ; String name = input.getString("请输入姓名:"); int age = input.getInt("请输入年龄:", "年龄必须是数字,"); Date date = input.getDate("请输入生日:","输入的不是日期,"); float salary = input.getFloat("请输入工资:", "输入的工资必须是数字,"); String sql = "INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,?,?,?,?) "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ;// 使用预处理的方式创建对象 pstmt.setString(1, name) ;// 第一个?号的内容 pstmt.setInt(2, age) ; // 第二个?号的内容 pstmt.setDate(3, new java.sql.Date(date.getTime())) ; pstmt.setFloat(4,salary) ; // 执行SQL语句,更新数据库 pstmt.executeUpdate(); // 4、关闭数据库 pstmt.close() ; conn.close(); } } ./ch23/JDBCproject1.0/wf/network/prepareddemo01/SelectDemo01.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; public class SelectDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null ; // 表示数据库的更新操作 ResultSet result = null ;// 表示接收数据库的查询结果 String sql = "SELECT pid,name,age,birthday,salary FROM person" ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ; // 执行SQL语句,查询数据库 result = pstmt.executeQuery() ; while(result.next()){// 是否有下一行数据 int pid = result.getInt(1) ; String name = result.getString(2) ; int age = result.getInt(3) ; Date birthday = result.getDate(4) ; float salary = result.getFloat(5) ; System.out.print("pid = " + pid + ";") ; System.out.print("name = " + name + ";") ; System.out.print("age = " + age + ";") ; System.out.print("birthday = " + birthday + ";") ; System.out.println("salary = " + salary + ";") ; } // 4、关闭数据库 result.close() ; pstmt.close() ; conn.close(); } } ./ch23/JDBCproject1.0/wf/network/prepareddemo01/SelectDemo02.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; public class SelectDemo02 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null ; // 表示数据库的更新操作 ResultSet result = null ;// 表示接收数据库的查询结果 String keyWord = "" ; String sql = "SELECT pid,name,age,birthday,salary FROM person WHERE name LIKE ? OR birthday LIKE ?" ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ; pstmt.setString(1,"%"+keyWord+"%") ; pstmt.setString(2,"%"+keyWord+"%") ; // 执行SQL语句,查询数据库 result = pstmt.executeQuery() ; while(result.next()){// 是否有下一行数据 int pid = result.getInt(1) ; String name = result.getString(2) ; int age = result.getInt(3) ; Date birthday = result.getDate(4) ; float salary = result.getFloat(5) ; System.out.print("pid = " + pid + ";") ; System.out.print("name = " + name + ";") ; System.out.print("age = " + age + ";") ; System.out.print("birthday = " + birthday + ";") ; System.out.println("salary = " + salary + ";") ; } // 4、关闭数据库 result.close() ; pstmt.close() ; conn.close(); } } ./ch23/JDBCproject1.0/wf/network/resultsetdemo01/ResultSetDemo01.java package wf.network.resultsetdemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; public class ResultSetDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 ResultSet result = null; //表示 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 result = stmt.executeQuery("SELECT pid,name,age,birthday,salary FROM person"); while (result.next()){ // 是否有下一行信息 int pid = result.getInt("pid") ; String name = result.getString("name"); int age = result.getInt("age"); Date birthday = result.getDate("birthday"); float salary = result.getFloat("salary"); System.out.print("pid=" + pid+";"); System.out.print("name=" + name+";"); System.out.print("age=" + age+";"); System.out.print("birthday=" + birthday+";"); System.out.println("salary=" + salary+";"); } result.close(); stmt.close(); // 4、关闭数据库 conn.close(); } } ./ch23/JDBCproject1.0/wf/network/resultsetdemo01/ResultSetDemo02.java package wf.network.resultsetdemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; public class ResultSetDemo02 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 ResultSet result = null; //表示 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 result = stmt.executeQuery("SELECT pid,name,age,birthday,salary FROM person"); while(result.next()){// 是否有下一行数据 int pid = result.getInt(1) ; String name = result.getString(2) ; int age = result.getInt(3) ; Date birthday = result.getDate(4) ; float salary = result.getFloat(5) ; System.out.print("pid = " + pid + ";") ; System.out.print("name = " + name + ";") ; System.out.print("age = " + age + ";") ; System.out.print("birthday = " + birthday + ";") ; System.out.println("salary = " + salary + ";") ; } result.close(); stmt.close(); // 4、关闭数据库 conn.close(); } } ./ch23/JDBCproject1.0/wf/network/trandemo01/TransactionDemo01.java package wf.network.trandemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class TransactionDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:ORCL"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); conn.setAutoCommit(false) ; // 取消自动提交 // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; try{ stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'张三',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'李四',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'王'五',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'赵六',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'孙七',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; // 执行SQL语句,更新数据库 int i[] = stmt.executeBatch() ; System.out.println(i.length); conn.commit() ;// 提交 }catch(Exception e){ conn.rollback() ;// 回滚 } // 4、关闭数据库 stmt.close() ; conn.close(); } } ./ch23/JDBCproject1.0/wf/network/updatedemo01/StatementDemo01.java package wf.network.updatedemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class StatementDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 stmt.executeUpdate("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'张三',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; // 4、关闭数据库 conn.close(); } } ./ch23/JDBCproject1.0/wf/network/updatedemo01/StatementDemo02.java package wf.network.updatedemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class StatementDemo02 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 stmt.executeUpdate("UPDATE person SET name='李四', age=33,birthday=sysdate,salary=8000.0 WHERE pid=2 ") ; // 4、关闭数据库 conn.close(); } } ./ch23/JDBCproject1.0/wf/network/updatedemo01/StatementDemo03.java package wf.network.updatedemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class StatementDemo03 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "wangfei"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 stmt.executeUpdate("DELETE FROM person WHERE pid=4 ") ; // 4、关闭数据库 conn.close(); } } ./ch23/���渚�23-10/浠g��23-10.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Date; public class InsertDemo { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null; // 表示数据库的更新操作 InputData input = new InputData() ; String name = input.getString("请输入姓名:"); int age = input.getInt("请输入年龄:", "年龄必须是数字,"); Date date = input.getDate("请输入生日:","输入的不是日期,"); float salary = input.getFloat("请输入工资:", "输入的工资必须是数字,"); String sql = "INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,?,?,?,?) "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ;// 使用预处理的方式创建对象 pstmt.setString(1, name) ;// 第一个?号的内容 pstmt.setInt(2, age) ; // 第二个?号的内容 pstmt.setDate(3, new java.sql.Date(date.getTime())) ; pstmt.setFloat(4,salary) ; // 执行SQL语句,更新数据库 pstmt.executeUpdate(); // 4、关闭数据库 pstmt.close() ; conn.close(); } } ./ch23/���渚�23-11/浠g��23-11.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; public class SelectDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null ; // 表示数据库的更新操作 ResultSet result = null ;// 表示接收数据库的查询结果 String sql = "SELECT pid,name,age,birthday,salary FROM person" ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ; // 执行SQL语句,查询数据库 result = pstmt.executeQuery() ; while(result.next()){// 是否有下一行数据 int pid = result.getInt(1) ; String name = result.getString(2) ; int age = result.getInt(3) ; Date birthday = result.getDate(4) ; float salary = result.getFloat(5) ; System.out.print("pid = " + pid + ";") ; System.out.print("name = " + name + ";") ; System.out.print("age = " + age + ";") ; System.out.print("birthday = " + birthday + ";") ; System.out.println("salary = " + salary + ";") ; } // 4、关闭数据库 result.close() ; pstmt.close() ; conn.close(); } } ./ch23/���渚�23-12/浠g��23-12.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; public class SelectDemo02 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null ; // 表示数据库的更新操作 ResultSet result = null ;// 表示接收数据库的查询结果 String keyWord = "" ; String sql = "SELECT pid,name,age,birthday,salary FROM person WHERE name LIKE ? OR birthday LIKE ?" ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ; pstmt.setString(1,"%"+keyWord+"%") ; pstmt.setString(2,"%"+keyWord+"%") ; // 执行SQL语句,查询数据库 result = pstmt.executeQuery() ; while(result.next()){// 是否有下一行数据 int pid = result.getInt(1) ; String name = result.getString(2) ; int age = result.getInt(3) ; Date birthday = result.getDate(4) ; float salary = result.getFloat(5) ; System.out.print("pid = " + pid + ";") ; System.out.print("name = " + name + ";") ; System.out.print("age = " + age + ";") ; System.out.print("birthday = " + birthday + ";") ; System.out.println("salary = " + salary + ";") ; } // 4、关闭数据库 result.close() ; pstmt.close() ; conn.close(); } } ./ch23/���渚�23-13/浠g��23-13.java package wf.network.prepareddemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class BatchInsertDemo { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null; // 表示数据库的更新操作 String sql = "INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,?,?,?,?) "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ;// 使用预处理的方式创建对象 for(int i=0;i<10;i++){ pstmt.setString(1, "lxh-" + i);// 第一个?号的内容 pstmt.setInt(2, 20 + i); // 第二个?号的内容 pstmt.setDate(3, new java.sql.Date(new java.util.Date().getTime())); pstmt.setFloat(4, 900*i); pstmt.addBatch() ; // 增加批处理 } // 执行SQL语句,更新数据库 int i[] = pstmt.executeBatch() ; System.out.println(i.length); // 4、关闭数据库 pstmt.close() ; conn.close(); } } ./ch23/���渚�23-14/浠g��23-14.java package wf.network.trandemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class TransactionDemo02 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:ORCL"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); conn.setAutoCommit(false) ; // 取消自动提交 // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; try{ stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'张三',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'李四',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'王'五',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'赵六',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; stmt.addBatch("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'孙七',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; // 执行SQL语句,更新数据库 int i[] = stmt.executeBatch() ; System.out.println(i.length); conn.commit() ;// 提交 }catch(Exception e){ conn.rollback() ;// 回滚 } // 4、关闭数据库 stmt.close() ; conn.close(); } } ./ch23/���渚�23-15/浠g��23-15.java package org.lxh.mysqldemo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Date; public class JDBCMySQL { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:mysql://localhost:3306/orcl"; // 连接数据库的用户名 public static final String DBUSER = "root"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 PreparedStatement pstmt = null; // 表示数据库的更新操作 String name = "张三"; int age = 30; Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1983-02-15"); float salary = 7000.0f; String sql = "INSERT INTO person(name,age,birthday,salary) VALUES (?,?,?,?) "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、PreparedStatement接口需要通过Connection接口进行实例化操作 pstmt = conn.prepareStatement(sql) ;// 使用预处理的方式创建对象 pstmt.setString(1, name) ;// 第一个?号的内容 pstmt.setInt(2, age) ; // 第二个?号的内容 pstmt.setDate(3, new java.sql.Date(date.getTime())) ; pstmt.setFloat(4,salary) ; // 执行SQL语句,更新数据库 pstmt.executeUpdate(); // 4、关闭数据库 pstmt.close() ; conn.close(); } } ./ch23/���渚�23-2/浠g��23-2.java package wf.network.JDBCproject01; import java.sql.Connection; import java.sql.DriverManager; public class ConnectJDBC { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); System.out.println(conn); // 4、关闭数据库 conn.close(); } } ./ch23/���渚�23-3/浠g��23-3.java package wf.network.updatedemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class StatementDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 stmt.executeUpdate("INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'张三',30,TO_DATE('1995-02-14','yyyy-mm-dd'),9000.0) ") ; // 4、关闭数据库 conn.close(); } }./ch23/���渚�23-4/浠g��23-4.java package wf.network.updatedemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class StatementDemo02 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 stmt.executeUpdate("UPDATE person SET name='李四', age=33,birthday=sysdate,salary=8000.0 WHERE pid=1 ") ; // 4、关闭数据库 conn.close(); } } ./ch23/���渚�23-5/浠g��23-5.java package wf.network.updatedemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class StatementDemo03 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 stmt.executeUpdate("DELETE FROM person WHERE pid=4 ") ; // 4、关闭数据库 conn.close(); } }./ch23/���渚�23-6/浠g��23-6.java package wf.network.resultsetdemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; public class ResultSetDemo01 { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null ; // 表示数据库的更新操作 ResultSet result = null; //表示 // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement() ; // 执行SQL语句,更新数据库 result = stmt.executeQuery("SELECT pid,name,age,birthday,salary FROM person"); while (result.next()){ // 是否有下一行信息 int pid = result.getInt("pid") ; String name = result.getString("name"); int age = result.getInt("age"); Date birthday = result.getDate("birthday"); float salary = result.getFloat("salary"); System.out.print("pid=" + pid+";"); System.out.print("name=" + name+";"); System.out.print("age=" + age+";"); System.out.print("birthday=" + birthday+";"); System.out.println("salary=" + salary+";"); } result.close(); stmt.close(); // 4、关闭数据库 conn.close(); } } ./ch23/���渚�23-8/浠g��23-8.java package wf.network.execdemo01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class InsertDemo { // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中 public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住 public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; // 连接数据库的用户名 public static final String DBUSER = "system"; // 连接数据库的密码 public static final String DBPASS = "java"; public static void main(String[] args) throws Exception { Connection conn = null; // 表示数据库的连接的对象 Statement stmt = null; // 表示数据库的更新操作 InputData input = new InputData() ; String name = input.getString("请输入姓名:"); int age = input.getInt("请输入年龄:", "年龄必须是数字,"); String date = input.getString("请输入生日:"); float salary = input.getFloat("请输入工资:", "输入的工资必须是数字,"); String sql = "INSERT INTO person(pid,name,age,birthday,salary) VALUES (perseq.nextval,'" + name + "'," + age + ",TO_DATE('" + date + "','yyyy-mm-dd')," + salary + ") "; System.out.println(sql) ; // 1、使用Class类加载驱动程序 Class.forName(DBDRIVER); // 2、连接数据库 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 3、Statement接口需要通过Connection接口进行实例化操作 stmt = conn.createStatement(); // 执行SQL语句,更新数据库 stmt.executeUpdate(sql); // 4、关闭数据库 conn.close(); } } ./ch24/FiveChessProject/org/liky/game/frame/FiveChessFrame.java package org.liky.game.frame; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JOptionPane; public class FiveChessFrame extends JFrame implements MouseListener, Runnable { // 取得屏幕的宽度 int width = Toolkit.getDefaultToolkit().getScreenSize().width; // 取得屏幕的高度 int height = Toolkit.getDefaultToolkit().getScreenSize().height; // 背景图片 BufferedImage bgImage = null; // 保存棋子的坐标 int x = 0; int y = 0; // 保存之前下过的全部棋子的坐标 // 其中数据内容 0: 表示这个点并没有棋子, 1: 表示这个点是黑子, 2:表示这个点是白子 int[][] allChess = new int[19][19]; // 标识当前应该黑棋还是白棋下下一步 boolean isBlack = true; // 标识当前游戏是否可以继续 boolean canPlay = true; // 保存显示的提示信息 String message = "黑方先行"; // 保存最多拥有多少时间(秒) int maxTime = 0; // 做倒计时的线程类 Thread t = new Thread(this); // 保存黑方与白方的剩余时间 int blackTime = 0; int whiteTime = 0; // 保存双方剩余时间的显示信息 String blackMessage = "无限制"; String whiteMessage = "无限制"; public FiveChessFrame() { // 设置标题 this.setTitle("五子棋"); // 设置窗体大小 this.setSize(500, 500); // 设置窗体出现位置 this.setLocation((width - 500) / 2, (height - 500) / 2); // 将窗体设置为大小不可改变 this.setResizable(false); // 将窗体的关闭方式设置为默认关闭后程序结束 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 为窗体加入监听器 this.addMouseListener(this); // 将窗体显示出来 this.setVisible(true); t.start(); t.suspend(); String imagePath = "" ; try { imagePath = System.getProperty("user.dir")+"/bin/image/background.jpg" ; bgImage = ImageIO.read(new File(imagePath.replaceAll("\\\\", "/"))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 刷新屏幕,防止开始游戏时出现无法显示的情况. this.repaint(); } public void paint(Graphics g) { // 双缓冲技术防止屏幕闪烁 BufferedImage bi = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); Graphics g2 = bi.createGraphics(); g2.setColor(Color.BLACK); // 绘制背景 g2.drawImage(bgImage, 1, 20, this); // 输出标题信息 g2.setFont(new Font("黑体", Font.BOLD, 20)); g2.drawString("游戏信息:" + message, 130, 60); // 输出时间信息 g2.setFont(new Font("宋体", 0, 14)); g2.drawString("黑方时间:" + blackMessage, 30, 470); g2.drawString("白方时间:" + whiteMessage, 260, 470); // 绘制棋盘 for (int i = 0; i < 19; i++) { g2.drawLine(10, 70 + 20 * i, 370, 70 + 20 * i); g2.drawLine(10 + 20 * i, 70, 10 + 20 * i, 430); } // 标注点位 g2.fillOval(68, 128, 4, 4); g2.fillOval(308, 128, 4, 4); g2.fillOval(308, 368, 4, 4); g2.fillOval(68, 368, 4, 4); g2.fillOval(308, 248, 4, 4); g2.fillOval(188, 128, 4, 4); g2.fillOval(68, 248, 4, 4); g2.fillOval(188, 368, 4, 4); g2.fillOval(188, 248, 4, 4); /* * //绘制棋子 x = (x - 10) / 20 * 20 + 10 ; y = (y - 70) / 20 * 20 + 70 ; * //黑子 g.fillOval(x - 7, y - 7, 14, 14); //白子 g.setColor(Color.WHITE) ; * g.fillOval(x - 7, y - 7, 14, 14); g.setColor(Color.BLACK) ; * g.drawOval(x - 7, y - 7, 14, 14); */ // 绘制全部棋子 for (int i = 0; i < 19; i++) { for (int j = 0; j < 19; j++) { if (allChess[i][j] == 1) { // 黑子 int tempX = i * 20 + 10; int tempY = j * 20 + 70; g2.fillOval(tempX - 7, tempY - 7, 14, 14); } if (allChess[i][j] == 2) { // 白子 int tempX = i * 20 + 10; int tempY = j * 20 + 70; g2.setColor(Color.WHITE); g2.fillOval(tempX - 7, tempY - 7, 14, 14); g2.setColor(Color.BLACK); g2.drawOval(tempX - 7, tempY - 7, 14, 14); } } } g.drawImage(bi, 0, 0, this); } public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub /* * System.out.println("X:"+e.getX()); System.out.println("Y:"+e.getY()); */ if (canPlay == true) { x = e.getX(); y = e.getY(); if (x >= 10 && x <= 370 && y >= 70 && y <= 430) { x = (x - 10) / 20; y = (y - 70) / 20; if (allChess[x][y] == 0) { // 判断当前要下的是什么颜色的棋子 if (isBlack == true) { allChess[x][y] = 1; isBlack = false; message = "轮到白方"; } else { allChess[x][y] = 2; isBlack = true; message = "轮到黑方"; } // 判断这个棋子是否和其他的棋子连成5连,即判断游戏是否结束 boolean winFlag = this.checkWin(); if (winFlag == true) { JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "黑方" : "白方") + "获胜!"); canPlay = false; } } else { JOptionPane.showMessageDialog(this, "当前位置已经有棋子,请重新落子!"); } this.repaint(); } } /* System.out.println(e.getX() + " -- " + e.getY()); */ // 点击 开始游戏 按钮 if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 70 && e.getY() <= 100) { int result = JOptionPane.showConfirmDialog(this, "是否重新开始游戏?"); if (result == 0) { // 现在重新开始游戏 // 重新开始所要做的操作: 1)把棋盘清空,allChess这个数组中全部数据归0. // 2) 将 游戏信息: 的显示改回到开始位置 // 3) 将下一步下棋的改为黑方 for (int i = 0; i < 19; i++) { for (int j = 0; j < 19; j++) { allChess[i][j] = 0; } } // 另一种方式 allChess = new int[19][19]; message = "黑方先行"; isBlack = true; blackTime = maxTime; whiteTime = maxTime; if (maxTime > 0) { blackMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600 * 60) + ":" + (maxTime - maxTime / 60 * 60); whiteMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600 * 60) + ":" + (maxTime - maxTime / 60 * 60); t.resume(); } else { blackMessage = "无限制"; whiteMessage = "无限制"; } this.canPlay = true; this.repaint(); } } // 点击 游戏设置 按钮 if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 120 && e.getY() <= 150) { String input = JOptionPane .showInputDialog("请输入游戏的最大时间(单位:分钟),如果输入0,表示没有时间限制:"); try { maxTime = Integer.parseInt(input) * 60; if (maxTime < 0) { JOptionPane.showMessageDialog(this, "请输入正确信息,不允许输入负数!"); } if (maxTime == 0) { int result = JOptionPane.showConfirmDialog(this, "设置完成,是否重新开始游戏?"); if (result == 0) { for (int i = 0; i < 19; i++) { for (int j = 0; j < 19; j++) { allChess[i][j] = 0; } } // 另一种方式 allChess = new int[19][19]; message = "黑方先行"; isBlack = true; blackTime = maxTime; whiteTime = maxTime; blackMessage = "无限制"; whiteMessage = "无限制"; this.canPlay = true; this.repaint(); } } if (maxTime > 0) { int result = JOptionPane.showConfirmDialog(this, "设置完成,是否重新开始游戏?"); if (result == 0) { for (int i = 0; i < 19; i++) { for (int j = 0; j < 19; j++) { allChess[i][j] = 0; } } // 另一种方式 allChess = new int[19][19]; message = "黑方先行"; isBlack = true; blackTime = maxTime; whiteTime = maxTime; blackMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600 * 60) + ":" + (maxTime - maxTime / 60 * 60); whiteMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600 * 60) + ":" + (maxTime - maxTime / 60 * 60); t.resume(); this.canPlay = true; this.repaint(); } } } catch (NumberFormatException e1) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(this, "请正确输入信息!"); } } // 点击 游戏说明 按钮 if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 170 && e.getY() <= 200) { JOptionPane.showMessageDialog(this, "这个一个五子棋游戏程序,黑白双方轮流下棋,当某一方连到五子时,游戏结束。"); } // 点击 认输 按钮 if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 270 && e.getY() <= 300) { int result = JOptionPane.showConfirmDialog(this, "是否确认认输?"); if (result == 0) { if (isBlack) { JOptionPane.showMessageDialog(this, "黑方已经认输,游戏结束!"); } else { JOptionPane.showMessageDialog(this, "白方已经认输,游戏结束!"); } canPlay = false; } } // 点击 关于 按钮 if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 320 && e.getY() <= 350) { JOptionPane.showMessageDialog(this, "本游戏由MLDN制作,有相关问题可以访问www.mldn.cn"); } // 点击 退出 按钮 if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 370 && e.getY() <= 400) { JOptionPane.showMessageDialog(this, "游戏结束"); System.exit(0); } } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } private boolean checkWin() { boolean flag = false; // 保存共有相同颜色多少棋子相连 int count = 1; // 判断横向是否有5个棋子相连,特点 纵坐标 是相同, 即allChess[x][y]中y值是相同 int color = allChess[x][y]; /* * if (color == allChess[x+1][y]) { count++; if (color == * allChess[x+2][y]) { count++; if (color == allChess[x+3][y]) { * count++; } } } */ // 通过循环来做棋子相连的判断 /* * int i = 1; while (color == allChess[x + i][y + 0]) { count++; i++; } * i = 1; while (color == allChess[x - i][y - 0]) { count++; i++; } if * (count >= 5) { flag = true; } // 纵向的判断 int i2 = 1 ; int count2 = 1 ; * while (color == allChess[x + 0][y + i2]) { count2++; i2++; } i2 = 1; * while (color == allChess[x - 0][y - i2]) { count2++; i2++; } if * (count2 >= 5) { flag = true ; } // 斜方向的判断(右上 + 左下) int i3 = 1 ; int * count3 = 1 ; while (color == allChess[x + i3][y - i3]) { count3++; * i3++; } i3 = 1; while (color == allChess[x - i3][y + i3]) { count3++; * i3++; } if (count3 >= 5) { flag = true ; } // 斜方向的判断(右下 + 左上) int i4 = * 1 ; int count4 = 1 ; while (color == allChess[x + i4][y + i4]) { * count4++; i4++; } i4 = 1; while (color == allChess[x - i4][y - i4]) { * count4++; i4++; } if (count4 >= 5) { flag = true ; } */ // 判断横向 count = this.checkCount(1, 0, color); if (count >= 5) { flag = true; } else { // 判断纵向 count = this.checkCount(0, 1, color); if (count >= 5) { flag = true; } else { // 判断右上、左下 count = this.checkCount(1, -1, color); if (count >= 5) { flag = true; } else { // 判断右下、左上 count = this.checkCount(1, 1, color); if (count >= 5) { flag = true; } } } } return flag; } // 判断棋子连接的数量 private int checkCount(int xChange, int yChange, int color) { int count = 1; int tempX = xChange; int tempY = yChange; while (x + xChange >= 0 && x + xChange <= 18 && y + yChange >= 0 && y + yChange <= 18 && color == allChess[x + xChange][y + yChange]) { count++; if (xChange != 0) xChange++; if (yChange != 0) { if (yChange > 0) yChange++; else { yChange--; } } } xChange = tempX; yChange = tempY; while (x - xChange >= 0 && x - xChange <= 18 && y - yChange >= 0 && y - yChange <= 18 && color == allChess[x - xChange][y - yChange]) { count++; if (xChange != 0) xChange++; if (yChange != 0) { if (yChange > 0) yChange++; else { yChange--; } } } return count; } public void run() { // TODO Auto-generated method stub // 判断是否有时间限制 if (maxTime > 0) { while (true) { if (isBlack) { blackTime--; if (blackTime == 0) { JOptionPane.showMessageDialog(this, "黑方超时,游戏结束!"); } } else { whiteTime--; if (whiteTime == 0) { JOptionPane.showMessageDialog(this, "白方超时,游戏结束!"); } } blackMessage = blackTime / 3600 + ":" + (blackTime / 60 - blackTime / 3600 * 60) + ":" + (blackTime - blackTime / 60 * 60); whiteMessage = whiteTime / 3600 + ":" + (whiteTime / 60 - whiteTime / 3600 * 60) + ":" + (whiteTime - whiteTime / 60 * 60); this.repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(blackTime + " -- " + whiteTime); } } } } ./ch24/FiveChessProject/org/liky/game/test/Test.java package org.liky.game.test; import org.liky.game.frame.FiveChessFrame; public class Test { public static void main(String[] args) { FiveChessFrame ff = new FiveChessFrame(); } } ./ch24/浠g��24-1.java package org.liky.game; import javax.swing.JFrame; public class Test { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 JFrame jf = new JFrame(); jf.setVisible(true); } } ./ch24/浠g��24-2.java package org.liky.game; import javax.swing.JFrame; public class Test { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 JFrame jf = new JFrame(); jf.setVisible(true); jf.setTitle("五子棋"); jf.setSize(200,100); jf.setLocation(200,100); } } ./ch24/浠g��24-3.java package org.liky.game; import javax.swing.JFrame; public class Test { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 JFrame jf = new JFrame(); jf.setVisible(true); jf.setTitle("五子棋"); jf.setSize(200,100); jf.setLocation(200,100); jf.setResizable(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } ./ch24/浠g��24-4.java package org.liky.game; import java.awt.Toolkit; import javax.swing.JFrame; public class Test { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 JFrame jf = new JFrame(); jf.setVisible(true); jf.setTitle("五子棋"); jf.setSize(200,100); jf.setLocation(200,100); jf.setResizable(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int width = Toolkit.getDefaultToolkit().getScreenSize().width; int height = Toolkit.getDefaultToolkit().getScreenSize().height; System.out.println("宽度为:"+ width); System.out.println("高度为:"+ height); } } ./ch24/浠g��24-5.java package org.liky.game; import java.awt.Toolkit; import javax.swing.JFrame; public class Test { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 JFrame jf = new JFrame(); jf.setVisible(true); jf.setTitle("五子棋"); jf.setSize(200,100); //jf.setLocation(200,100); jf.setResizable(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int width = Toolkit.getDefaultToolkit().getScreenSize().width; int height = Toolkit.getDefaultToolkit().getScreenSize().height; System.out.println("宽度为:"+ width); System.out.println("高度为:"+ height); jf.setLocation((width-200)/2,(height-100)/2); } } ./ch24/浠g��24-6.java package org.liky.game.test; import org.liky.game.frame.FiveChessFrame; public class Test { public static void main(String[] args) { FiveChessFrame ff = new FiveChessFrame(); } } ./ch24/浠g��24-7.java package org.liky.game.frame; import java.awt.Toolkit; import javax.swing.JFrame; public class FiveChessFrame extends JFrame { // 取得屏幕的宽度 int width = Toolkit.getDefaultToolkit().getScreenSize().width; // 取得屏幕的高度 int height = Toolkit.getDefaultToolkit().getScreenSize().height; public FiveChessFrame() { // 设置标题 this.setTitle("五子棋"); // 设置窗体大小 this.setSize(500, 500); // 设置窗体出现位置 this.setLocation((width - 500) / 2, (height - 500) / 2); // 将窗体设置为大小不可改变 this.setResizable(false); // 将窗体的关闭方式设置为默认关闭后程序结束 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 将窗体显示出来 this.setVisible(true); } } ./ch24/浠g��24-8.java package org.liky.game; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JOptionPane; import org.liky.game.frame.FiveChessFrame; public class Test { public static void main(String[] args) { FiveChessFrame ff = new FiveChessFrame(); JOptionPane.showMessageDialog(ff, "我的信息"); int result=JOptionPane.showConfirmDialog(ff,"我的确认信息:现在要开始游戏吗?" ); if (result == 0){ JOptionPane.showMessageDialog(ff, "游戏开始"); } if (result == 1){ JOptionPane.showMessageDialog(ff, "游戏结束"); } if (result == 2){ JOptionPane.showMessageDialog(ff, "请重新选择"); } String username = JOptionPane.showInputDialog("请输入你的姓名: "); if (username != null ){ System.out.println(username); JOptionPane.showMessageDialog(ff,"输入的姓名为: " + username ); }else { JOptionPane.showMessageDialog(ff, "请重新输入你的姓名!"); } } } ./ch24/浠g��24-9.java package org.liky.game.frame; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JOptionPane; public class FiveChessFrame extends JFrame implements MouseListener { // 取得屏幕的宽度 int width = Toolkit.getDefaultToolkit().getScreenSize().width; // 取得屏幕的高度 int height = Toolkit.getDefaultToolkit().getScreenSize().height; // 保存棋子的坐标 int x = 0; int y = 0; // 保存之前下过的全部棋子的坐标 // 其中数据内容 0: 表示这个点并没有棋子, 1: 表示这个点是黑子, 2:表示这个点是白子 int[][] allChess = new int[19][19]; // 标识当前应该黑棋还是白棋下下一步 boolean isBlack = true; // 标识当前游戏是否可以继续 boolean canPlay = true; // 保存显示的提示信息 String message = "黑方先行"; // 保存最多拥有多少时间(秒) int maxTime = 0; // 保存黑方与白方的剩余时间 int blackTime = 0; int whiteTime = 0; // 保存双方剩余时间的显示信息 String blackMessage = "无限制"; String whiteMessage = "无限制"; public FiveChessFrame() throws HeadlessException { // 设置标题 this.setTitle("五子棋"); // 设置窗体大小 this.setSize(500, 500); // 设置窗体出现位置 this.setLocation((width - 500) / 2, (height - 500) / 2); // 将窗体设置为大小不可改变 this.setResizable(false); // 将窗体的关闭方式设置为默认关闭后程序结束 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 为窗体加入监听器 this.addMouseListener(this); // 将窗体显示出来 this.setVisible(true); } public void mouseClicked(MouseEvent arg0) { // TODO 自动生成方法存根 JOptionPane.showMessageDialog(this,"鼠标单击"); } public void mouseEntered(MouseEvent arg0) { // TODO 自动生成方法存根 } public void mouseExited(MouseEvent arg0) { // TODO 自动生成方法存根 } public void mousePressed(MouseEvent arg0) { // TODO 自动生成方法存根 } public void mouseReleased(MouseEvent arg0) { // TODO 自动生成方法存根 } } ./ch25/InfoProject/src/org/lxh/info/dao/impl/IPersonDAOImpl.java package org.lxh.info.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import org.lxh.info.dao.IPersonDAO; import org.lxh.info.vo.Person; public class IPersonDAOImpl implements IPersonDAO { private Connection conn = null; public IPersonDAOImpl(Connection conn) { this.conn = conn; } public boolean doCreate(Person person) throws Exception { boolean flag = false; PreparedStatement pstmt = null; String sql = "INSERT INTO person(pid,name,age,birthday,address)" + " VALUES (myseq.nextval,?,?,?,?)"; try { pstmt = this.conn.prepareStatement(sql); pstmt.setString(1, person.getName()); pstmt.setInt(2, person.getAge()); pstmt.setDate(3, new java.sql.Date(person.getBirthday().getTime())); pstmt.setString(4, person.getAddress()); int len = pstmt.executeUpdate(); if (len > 0) { flag = true; } } catch (Exception e) { throw e; } finally { try { pstmt.close(); } catch (Exception e) { throw e; } } return flag; } public boolean doDelete(int pid) throws Exception { boolean flag = false; PreparedStatement pstmt = null; String sql = "DELETE FROM person WHERE pid=?"; try { pstmt = this.conn.prepareStatement(sql); pstmt.setInt(1, pid); int len = pstmt.executeUpdate(); if (len > 0) { flag = true; } } catch (Exception e) { throw e; } finally { try { pstmt.close(); } catch (Exception e) { throw e; } } return flag; } public boolean doUpdate(Person person) throws Exception { boolean flag = false; PreparedStatement pstmt = null; String sql = "UPDATE person SET name=?,age=?,birthday=?,address=? WHERE pid=?"; try { pstmt = this.conn.prepareStatement(sql); pstmt.setString(1, person.getName()); pstmt.setInt(2, person.getAge()); pstmt.setDate(3, new java.sql.Date(person.getBirthday().getTime())); pstmt.setString(4, person.getAddress()); pstmt.setInt(5, person.getPid()); int len = pstmt.executeUpdate(); if (len > 0) { flag = true; } } catch (Exception e) { throw e; } finally { try { pstmt.close(); } catch (Exception e) { throw e; } } return flag; } public List<Person> findAll(String keyWord) throws Exception { List<Person> all = new ArrayList<Person>(); PreparedStatement pstmt = null; String sql = "SELECT pid,name,age,birthday,address FROM person " + "WHERE name LIKE ? OR age LIKE ? OR birthday LIKE ? OR address LIKE ?"; try { pstmt = this.conn.prepareStatement(sql); pstmt.setString(1, "%" + keyWord + "%"); // 模糊查询 pstmt.setString(2, "%" + keyWord + "%"); // 模糊查询 pstmt.setString(3, "%" + keyWord + "%"); // 模糊查询 pstmt.setString(4, "%" + keyWord + "%"); // 模糊查询 ResultSet rs = pstmt.executeQuery(); // 执行查询 Person per = null; while (rs.next()) { // 如果有查询的结果,则可以向下执行 per = new Person(); per.setPid(rs.getInt(1)); per.setName(rs.getString(2)); per.setAge(rs.getInt(3)); per.setBirthday(rs.getDate(4)); per.setAddress(rs.getString(5)); all.add(per); // 向集合中插入内容 } } catch (Exception e) { throw e; } finally { try { pstmt.close(); } catch (Exception e) { throw e; } } return all; } public Person findById(int pid) throws Exception { Person per = null; PreparedStatement pstmt = null; String sql = "SELECT pid,name,age,birthday,address FROM person WHERE pid=?"; try { pstmt = this.conn.prepareStatement(sql); pstmt.setInt(1, pid); ResultSet rs = pstmt.executeQuery(); // 执行查询 if (rs.next()) { // 如果有查询的结果,则可以向下执行 per = new Person(); per.setPid(rs.getInt(1)); per.setName(rs.getString(2)); per.setAge(rs.getInt(3)); per.setBirthday(rs.getDate(4)); per.setAddress(rs.getString(5)); } } catch (Exception e) { throw e; } finally { try { pstmt.close(); } catch (Exception e) { throw e; } } return per; } } ./ch25/InfoProject/src/org/lxh/info/dao/IPersonDAO.java package org.lxh.info.dao; import java.util.List; import org.lxh.info.vo.Person; public interface IPersonDAO { /** * 数据库的增加操作 * @param person * @return * @throws Exception */ public boolean doCreate(Person person) throws Exception; /** * 数据库的修改操作 * @param person * @return * @throws Exception */ public boolean doUpdate(Person person) throws Exception; /** * 数据库的删除操作 * @param pid * @return * @throws Exception */ public boolean doDelete(int pid) throws Exception; /** * 根据ID查询数据库 * @param pid * @return * @throws Exception */ public Person findById(int pid) throws Exception; /** * 查询全部的记录 * @param keyWord * @return * @throws Exception */ public List<Person> findAll(String keyWord) throws Exception; } ./ch25/InfoProject/src/org/lxh/info/dao/proxy/IPersonDAOProxy.java package org.lxh.info.dao.proxy; import java.util.List; import org.lxh.info.dao.IPersonDAO; import org.lxh.info.dao.impl.IPersonDAOImpl; import org.lxh.info.dbc.DatabaseConnection; import org.lxh.info.vo.Person; public class IPersonDAOProxy implements IPersonDAO { private DatabaseConnection dbc = null; private IPersonDAO dao = null; public IPersonDAOProxy() { this.dbc = new DatabaseConnection(); this.dao = new IPersonDAOImpl(this.dbc.getConnection()); } public boolean doCreate(Person person) throws Exception { boolean flag = false; try { flag = this.dao.doCreate(person); } catch (Exception e) { throw e; } finally { this.dbc.close(); } return flag; } public boolean doDelete(int pid) throws Exception { boolean flag = false; try { flag = this.dao.doDelete(pid); } catch (Exception e) { throw e; } finally { this.dbc.close(); } return flag; } public boolean doUpdate(Person person) throws Exception { boolean flag = false; try { flag = this.dao.doUpdate(person); } catch (Exception e) { throw e; } finally { this.dbc.close(); } return flag; } public List<Person> findAll(String keyWord) throws Exception { List<Person> all = null; try { all = this.dao.findAll(keyWord); } catch (Exception e) { throw e; } finally { this.dbc.close(); } return all; } public Person findById(int pid) throws Exception { Person per = null; try { per = this.dao.findById(pid); } catch (Exception e) { throw e; } finally { this.dbc.close(); } return per; } } ./ch25/InfoProject/src/org/lxh/info/dbc/DatabaseConnection.java package org.lxh.info.dbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; public static final String DBUSER = "system"; public static final String DBPASSWORD = "root"; private Connection conn = null; public DatabaseConnection() { try { Class.forName(DBDRIVER); this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public Connection getConnection() { return this.conn; } public void close() { if (this.conn != null) { try { this.conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ./ch25/InfoProject/src/org/lxh/info/factory/DAOFactory.java package org.lxh.info.factory; import org.lxh.info.dao.IPersonDAO; import org.lxh.info.dao.proxy.IPersonDAOProxy; public class DAOFactory { public static IPersonDAO getIPersonDAOInstance() { return new IPersonDAOProxy(); } } ./ch25/InfoProject/src/org/lxh/info/menu/Menu.java package org.lxh.info.menu; import org.lxh.info.operate.PersonOperate; import org.lxh.info.util.InputData; public class Menu { public Menu() { while (true) { this.show(); } } public void show() { // 显示菜单 System.out.println("======== 人员管理系统 ========="); System.out.println("[1]、增加信息"); System.out.println("[2]、修改信息"); System.out.println("[3]、删除信息"); System.out.println("[4]、查看信息"); System.out.println("[5]、检索信息"); System.out.println("[0]、退出系统\n\n\n"); int ch = new InputData().getInt("请选择:", "选项必须是数字"); switch (ch) { case 0: { System.out.println("bye bye."); System.exit(1); } case 1: { PersonOperate.insert(); break; } case 2: { PersonOperate.update(); break; } case 3: { PersonOperate.delete(); break; } case 4: { PersonOperate.findall(); break; } case 5: { PersonOperate.search(); break; } default: { System.out.println("请选择正确的选项。"); } } } } ./ch25/InfoProject/src/org/lxh/info/operate/PersonOperate.java package org.lxh.info.operate; import java.util.Date; import java.util.Iterator; import java.util.List; import org.lxh.info.factory.DAOFactory; import org.lxh.info.util.InputData; import org.lxh.info.vo.Person; public class PersonOperate { public static void insert() { Person per = new Person(); InputData input = new InputData(); String name = input.getString("请输入人员的姓名:"); int age = input.getInt("请输入人员的年龄:", "年龄必须是数字,"); Date date = input.getDate("请输入人员的生日:", "输入的日期格式不正确,"); String address = input.getString("请输入人员的住址:"); per.setName(name); per.setAddress(address); per.setAge(age); per.setBirthday(date); try { DAOFactory.getIPersonDAOInstance().doCreate(per); System.out.println("人员信息增加成功!"); } catch (Exception e) { System.out.println("人员信息增加失败!"); } } public static void update() { // 在修改数据之前最好先将数据查询出来 Person per = null; InputData input = new InputData(); int pid = input.getInt("请输入要修改人员的编号:", "编号必须是数字,"); try { per = DAOFactory.getIPersonDAOInstance().findById(pid); } catch (Exception e1) { } if (per != null) { String name = input.getString("请输入新的人员的姓名(原姓名是:" + per.getName() + "):"); int age = input.getInt("请输入新的人员的年龄(原年龄是:" + per.getAge() + "):", "年龄必须是数字,"); Date date = input.getDate("请输入新的人员的生日(原生日是:" + per.getBirthday() + "):", "输入的日期格式不正确,"); String address = input.getString("请输入新的人员的住址(原住址是:" + per.getAddress() + "):"); per.setName(name); per.setAddress(address); per.setAge(age); per.setBirthday(date); try { DAOFactory.getIPersonDAOInstance().doUpdate(per); System.out.println("人员信息修改成功!"); } catch (Exception e) { System.out.println("人员信息修改失败!"); } } else { System.out.println("没有此人员信息。"); } } public static void delete() { InputData input = new InputData(); int pid = input.getInt("请输入要修改人员的编号:", "编号必须是数字,"); try { DAOFactory.getIPersonDAOInstance().doDelete(pid); System.out.println("人员信息删除成功!"); } catch (Exception e) { System.out.println("人员信息删除失败!"); } } public static void findall() { List<Person> all = null; try { all = DAOFactory.getIPersonDAOInstance().findAll(""); } catch (Exception e) { e.printStackTrace() ; } Iterator<Person> iter = all.iterator(); while (iter.hasNext()) { Person per = iter.next(); System.out.println(per.getPid() + "," + per.getName() + "," + per.getAge() + "," + per.getBirthday() + "," + per.getAddress()); } } public static void search() { List<Person> all = null; String kw = new InputData().getString("请输入检索的关键字:"); try { all = DAOFactory.getIPersonDAOInstance().findAll(kw); } catch (Exception e) { } Iterator<Person> iter = all.iterator(); while (iter.hasNext()) { Person per = iter.next(); System.out.println(per.getPid() + "," + per.getName() + "," + per.getAge() + "," + per.getBirthday() + "," + per.getAddress()); } } } ./ch25/InfoProject/src/org/lxh/info/test/Test.java package org.lxh.info.test; import org.lxh.info.menu.Menu; public class Test { public static void main(String[] args) throws Exception { new Menu(); } } ./ch25/InfoProject/src/org/lxh/info/util/InputData.java package org.lxh.info.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class InputData { private Scanner scan = null; // 输入数据 public InputData() { this.scan = new Scanner(System.in); // 输入数据实例化 } public String getString(String info) { String str = null; System.out.print(info); if (this.scan.hasNext()) { str = this.scan.next(); // 接收内容 } return str; } public int getInt(String info, String errMsg) { int temp = 0; System.out.print(info); if (this.scan.hasNextInt()) { temp = this.scan.nextInt(); // 接收内容 } else { System.out.print(errMsg); } return temp; } public Date getDate(String info, String errMsg) { java.util.Date date = null; System.out.print(info); if (this.scan.hasNext("\\d{4}-\\d{2}-\\d{2}")) { String str = this.scan.next("\\d{4}-\\d{2}-\\d{2}"); try { date = new SimpleDateFormat("yyyy-MM-dd").parse(str); } catch (ParseException e) { e.printStackTrace(); } } else { System.out.print(errMsg); } return date; } } ./ch25/InfoProject/src/org/lxh/info/vo/Person.java package org.lxh.info.vo; import java.util.Date; public class Person { // 本类可以很好的映射一个表的数据 private int pid; private String name; private int age; private Date birthday; private String address; public Person() { super(); } public Person(int pid, String name, int age, Date birthday, String address) { super(); this.pid = pid; this.name = name; this.age = age; this.birthday = birthday; this.address = address; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
《Java从入门到精通》src9-25的更多相关文章
- 《Java从入门到精通》src0-8
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello wo ...
- cucumber java从入门到精通(3)简单实现及断言
cucumber java从入门到精通(3)简单实现及断言 上一节里我们定义了step的java代码实现文件,step就是测试步骤及断言的集合,我们先定义出来,以后可以驱动开发以及在持续集成时重用. ...
- 《JAVA 从入门到精通》 - 正式走向JAVA项目开发的路
以前很多时候会开玩笑,说什么,三天学会PHP,七天精通Nodejs,xx天学会xx ... 一般来说,这样子说的多半都带有一点讽刺的意味,我也基本上从不相信什么快速入门.我以前在学校的时候自觉过很多门 ...
- 《java从入门到精通》学习记录
目录 <Java从入门到精通>学习记录 3 基础的基础部分: 3 一. 常量与变量 3 1. 掌握: 3 (1) .常量与变量的声明方式: 3 (2) .变量的命名规则: 3 (3) .变 ...
- cucumber java从入门到精通(4)Scenario Outline及数据驱动
cucumber java从入门到精通(4)Scenario Outline及数据驱动 到目前为止,我们的TodoList类工作良好,不过离我们的预期--任务清单系统还是有不少差距,究其原因不过如下: ...
- cucumber java从入门到精通(2)用代码定义步骤
cucumber java从入门到精通(2)用代码定义步骤 上一节里我们定义了feature文件,feature文件就是自然语言描述的用例文件,它有一定的章法,具体的潜规则是: 使用Feature关键 ...
- cucumber java从入门到精通(1)初体验
cucumber java从入门到精通(1)初体验 cucumber在ruby环境下表现让人惊叹,作为BDD框架的先驱,cucumber后来被移植到了多平台,有cucumber-js以及我们今天要介绍 ...
- Java从入门到精通一步到位!
Java作为近几年来非常火的编程语言,转行来做Java的人不计其数,但如今真正的人才仍然匮乏,所以学习Java一定要有一个系统的学习规划课程.阿里云大学帮您规划Java学习路线可以帮助您从一个小白成长 ...
- 【java从入门到精通】day-06-基本运算符-自增自减运算符
1.运算符 java语言支持如下运算符: 算术运算符:+,-,*,/,%,++,-- 赋值运算符:= 关系运算符:>,<,>=,<=,==,!=,instanceof 逻辑运算 ...
随机推荐
- html向servlet传乱码解决办法
html 设置为utf-8格式 <meta http-equiv="content-type" content="text/html;charset=UTF-8&q ...
- Chapter 11 迪米特法则
迪米特法则也叫最少知识原则:如果两个类不必彼此直接通信,那么这两个类就不应当发生直接的相互作用.如果其中一个类需要调用另一个类的某一个方法的话,可以通过第三者转发这个调用. 迪米特法则首先强调的前提是 ...
- python测试框架总结
最流行的有unittest和nose 其他的请看http://wiki.python.org/moin/PythonTes... 中Unit Testing Tools部分 py.test unitt ...
- guozhongCrawler的是一个无须配置、便于二次开发
guozhongCrawler的是一个无须配置.便于二次开发的爬虫开源框架,它提供简单灵活的API,只需少量代码即可实现一个爬虫.模块化设计完全 面向业务提供接口,功能覆盖整个爬虫的生命周期(链接提取 ...
- Google Map Android api V2 中使用MapView遇到CameraUpdateFactory is not initialized!的解决办法
先说一下 Map V2 API Key 的问题吧: 在打包APP时需要自己生成一个XXX.keystore 用这个密室库生成的SHA1去申请的key 作为AndroidManifest.xml 中的K ...
- poj 2114 Boatherds 树的分治
还是利用点的分治的办法来做,统计的办法不一样了,我的做法是排序并且标记每个点属于哪颗子树. #include <iostream> #include <cstdio> #inc ...
- windows下以指定用户访问SMB服务器进行读写
需求:最近要开发某系统前端界面,但是该系统是部署在linux服务器上,前端是用php开发,实时调试运行需要linux下系统环境支持, 每次修改都需要手动传到服务器上,尤其是debug阶段,每修改一点就 ...
- [ExtJS5学习笔记]第十五节 Extjs5表格显示不友好?panel的frame属性在作怪
本文地址:http://blog.csdn.net/sushengmiyan/article/details/39057243 sencha官方API:http://docs.sencha.com/e ...
- android armeabi与armeabi-v7a
我在armeabi下增加了百度的库: libBaiduMapSDK_v2_4_1.so 可是却报错说找不到库.我发如今libs下还有另外一个目录: armeabi-v7a 然后我把libBaiduMa ...
- Smarty - 安装+入门小例子
环境: smarty 1.在http://www.smarty.net/download下载最新smarty包,window选择zips,linux下选择tar.gz.以windows为例,下载后解压 ...