java 代码练习合集

zhangpinzp 贡献于2014-09-20

作者 test11  创建于2012-06-06 01:30:27   修改者test11  修改于2014-04-27 11:55:19字数68292

文档摘要:java代码练习合集
关键词:

 java代码练习合集 1.经典的helloWorld程序: public class HelloWorld{ public static void main(String[] args){ //int 年龄=20; System.out.println("HelloWorld!!!这是我的第一个Java程序"); System.out.println("HelloWorld!!!这是我的第一个Java程序"); System.out.println("HelloWorld!!!这是我的第一个Java程序"); } } ---------------------------------------------------------------------------------------------------------------------- public class Test1{ public static void main(String[] args){ System.out.println("Hello World!"); } } 2.4类8种: public class Test1{ public static void main(String[] args) { long l = 20L; int a = 5; short s = 6; byte b = 8; double d = 3.14; float f = 3.14f; char ch = 'a'; boolean flag = true; boolean flag1 = false; String name = "zhangsan"; System.out.println(l+","+a); } } -------------------------------------------------------------------------------------------------- public class Test2 { public static void main(String[] args){ final double PI = 3.14; final int I ; I = 5; //System.out.println("常量\n的值是:"+PI+I); //System.out.println("常量的值是:"+(PI+I)); String path = "d:\\javacode\\ch2\\Test2.java"; System.out.println("转义字符练习:\n\'a\'是一个字符,\"a\"是一个字符串"); } } java代码练习合集 public class Test3{ public static void main(String[] args){ int a = 6; int b = 4; float f = 3.0f; //System.out.println(a/b); //System.out.println(b/f); //System.out.println(f/0); System.out.println(f%0); 结果为: 1 1.3333334 Infinity NaN } } public class Test4{ public static void main(String[] args){ int a = 458; int m,n,k; m = a/100; n = a/10%10; k = a%10; System.out.println("m = "+m); System.out.println("n = "+n); System.out.println("k = "+k); } } 结果是:m = 4 n = 5 k = 8 public class Test5{ public static void main(String[] args){ int a = 6; int b = ++a+5; //int b; //a = a+1; //b = a+5 java代码练习合集 //b=? //a=? System.out.println("a = "+a+" b = "+b); int m = 0; int n = 5+m++; //int n = 5+m; //m = m+1; System.out.println("m = "+m+" n = "+n); } } a = 7 b = 12 m = 1 n = 5 public class Test6{ public static void main(String[] args) { int yearsold = 23; System.out.println("One year later:"); System.out.println("your years old is "+yearsold++);//23/24 yearsold=yearsold+1; System.out.println("Print again:"); System.out.println("your years old is "+yearsold); int temp = 23; System.out.println(temp>yearsold); } } public class Test7{ public static void main(String[] args) { int a = 1; //boolean b = a++==5||++a>7; //System.out.println("b = "+b+" a = "+a); //写一个判断闰年的表达式,如果一个年份能被4整除切不能被100整除或者能被400整除,则该年份为闰年 ///int year = 2012; //boolean leapYear = ((year%4==0)&&(year%100!=0))||(year%400==0); //System.out.println(leapYear); java代码练习合集 int b = 1; //a =a+b a = 2 //b =b-a; b = -1 //a =a+b a = 1 System.out.println("b = "+b+" a = "+a);//a=1 b=-1 } } public class Test8{ public static void main(String[] args){ int m = 6; int n = 7; int k = -5; int max = (m>=n?m:n)>=k?(m>=n?m:n):k; int min = (m<=n?m:n)<=k?(m>=n?m:n):k; System.out.println("max = "+max); System.out.println("min = "+min); double d = Math.sqrt(16); } } public class Test9{ public static void main(String[] args){ ///////////强制转换//////////////////// double r = 5; final double PI = 3.14; double area = PI*r*r; double p = PI*2*r; int a = (int)(area+p); System.out.println("area = "+a); ////////////隐含转换//////////////////// double d = 4.5; int i = 5; double sum = i+d;//i在与d求和之前,系统会自动将其类型转换成double double d1 = 4.5f;//隐含转换 float f = (float)4.5;//强制转换 char ch = 'a';//ascii:97 int m = ch+4; char ch1 = (char)m; System.out.println("m = "+m); java代码练习合集 System.out.println("ch1 = "+ch1); double value = Math.abs(-5); System.out.println("value = "+value); double max = Math.max(-1,Math.max(2,Math.max(4,6))); } } public class Test10{ public static void main(String[] args) { { double a = 4; double b = 5; double c = 1; double x1 = (-b+Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a); double x2 = (-b-Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a); System.out.println("x1 = "+x1); System.out.println("x2 = "+x2); } { double a = 4; double b = 3; double c = 5; double s = (a+b+c)/2; double area = Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.println("area = "+area); } } } public class Test11 { /*public static void main(String[] args) { int a = 5; int b = 5; boolean f1 = a++<5&&a++>5; boolean f2 = b++<5&b++>5; System.out.println("f1 = "+f1+",a = "+a); System.out.println("f2 = "+f2+",b = "+b); double d = 3.2D; float f = 3.2F; } */ java代码练习合集 private static int a = 0; public static void main(String[] args) { modify(a); System.out.println(a); } public static void modify(int a) { a++; a+=5; } } public class Test1 { public static void main(String[] args) { for(int i = 0;i<10;i++){ System.out.println("Hello World!"); } //for循环案例一:打印1,2,3,4....100 for(int i = 1;i<=100;i++){ System.out.println(i); } //for循环案例二:打印100,98,96...2 for(int i = 100;i>=2;i-=2){ System.out.println(i); } //分别求1,2,3,4...100中奇数的和与偶数的和 int sum1 = 0; for(int i = 1;i<=99;i+=2){ sum1 = sum1+i; //sum1+=i; } int sum2 = 0; for(int i = 2;i<=100;i+=2){ sum2 = sum2+i; //sum1+=i; } java.util.List list = new java.util.ArrayList(); list.add("aaa"); list.add("aaa"); list.add("aaa"); list.add("aaa"); for(String str:list){ java代码练习合集 System.out.println(str); } } } public class Test2{ public static void main(String[] args){ for(String str:args){ //System.out.println("test........"); System.out.println(str); } } } public class Test3{ public static void main(String[] args) { //求1+2+...+100 int i = 1; int sum = 0; while(i<=100){ sum+=i; i++; } System.out.println("sum = "+sum); /////////////////////////////////////////////// //输出 1 1 2 3 5 8 13 21 34......斐波那契数列,最后一项的值不大于10000 // m n k // m n k // m n k //第一项和第二项的的值都是1,从第三项开始每一项都等于前两项的和 int m = 1; int n = 1; int k = m+n; System.out.println(m); System.out.println(n); while(k<=10000){ System.out.println(k); m = n; n = k; k = m+n; } } } public class Test4 { java代码练习合集 public static void main(String[] args) { //求1+2+...+100 int i = 1; int sum = 0; do{ sum+=i; i++; }while(i<=100); System.out.println("sum = "+sum); int m = 1; int n = 1; int k = m+n; do{ System.out.println(k); m = n; n = k; k = m+n; }while(k<=10000); } } public class Test5{ public static void main(String[] args) { //给定两个数比较大小 int a = 5; int b = -6; int max; if(a>b){ max = a; }else{ max = b; } System.out.println("max = "+max); //给定三个数求三个数中最大的一个 int m = 30; int n = 150; int k = 80; /* if(m<=n){ m = n; } if(m<=k){ m = k; java代码练习合集 } System.out.println("max value = "+m); */ //给定三个不等的数按从小到大的顺序排序 if(m>n){ if(m>k){ if(k>n){ System.out.println("m>k>n"); }else{ System.out.println("m>n>k"); } }else{//mm>n"); } }else{//mk>m"); }else{ System.out.println("n>m>k"); } }else{ System.out.println("k>n>m"); } } } } public class Test6 { public static void main(String[] args) { int a = 5; if(a>0){ System.out.println("Hello World!"); System.out.println("Hello World!"); } else{ System.out.println("Hello"); System.out.println("Hello"); } for(int i = 1;i<=100;i++){ java代码练习合集 System.out.print(i+"\t"); if(i%10==0){ System.out.println(); } } //打印水仙花数,水仙花数是一个三位数,如果一个三位数等于百位、十位、个位的立方和,这个三位数称为水仙花数。 int bai,shi,ge; for(int i = 100;i<1000;i++){ bai = i/100; shi = i/10%10; ge = i%10; if(i==Math.pow(bai,3)+Math.pow(shi,3)+Math.pow(ge,3)){ System.out.println(i); } } } } public class Test7 { public static void main(String[] args) { /*int a = 100; if(a>=0){ System.out.println("One"); } else if(a>=50){ System.out.println("Tow"); } else if(a>=90){ System.out.println("Three"); } else if(a>=100){ System.out.println("Four"); } else{ System.out.println("Other"); } */ //给定一个百分制成绩,显示其5分制成绩 // A a 90~100 // B b 80~89 // C c 70~79 // D d 60~69 java代码练习合集 // E e 0~59 //其他成绩错误 //标准输入对象 java.util.Scanner sc = new java.util.Scanner(System.in); //int score = 199; while(true){ System.out.println("请输入百分制成绩,成绩应该在0~100之间,如果成绩小于0则退出系统"); //通过标准输入对象输入整数给变量score赋值 int score = sc.nextInt(); if(score>=90&&score<=100){ System.out.println("A or a"); }else if(score>=80&&score<=89){ System.out.println("B or b"); }else if(score>=70&&score<=79){ System.out.println("C or c"); } else if(score>=60&&score<=69){ System.out.println("D or d"); }else if(score>=0&&score<=59){ System.out.println("E or e"); }else if(score<0){ //结束进程退出 System.exit(0); } else{ System.out.println("Your score is error!!!!!!"); } } //作业1:给定一个5分制成绩输出百分制成绩 } } public class Test8 { public static void main(String[] args) { char ch = 'a'; switch(ch){ case 'A': case 'a': System.out.println("90~100"); break; java代码练习合集 case 'B': System.out.println("80~89"); break; case 'C': System.out.println("70~79"); break; case 'D': System.out.println("60~69"); break; case 'E': System.out.println("0~59"); break; default: System.out.println("error........"); break; } } } public class Test9 { public static void main(String[] args) { int score = 99; /* 100/10 99/10 98 .... 90/10 */ switch(score/10){ case 10: case 9: System.out.println("A a"); break; case 8: System.out.println("B b"); break; case 7: System.out.println("C c"); break; case 6: java代码练习合集 System.out.println("D d"); case 5: case 4: case 3: case 2: case 1: case 0: System.out.println("E e"); break; default: System.out.println("error....."); break; } //给定月份显示天数 } } public class Test10 { public static void main(String[] args){ int year = 2012; int month = 2; int days; boolean leapYear = year%4==0&&year%100!=0||year%400==0; switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if(leapYear){ days = 29; } java代码练习合集 else{ days = 28; } break; default: days = 0; break; } System.out.println("days = "+days); } } class Test11{ public static void main(String[] args) { String str = "abc"; switch(str){ case "abc": System.out.println("abc"); break; } } } public class Test12 { public static void main(String[] args) { for(int i = 1;i<=9;i++){ for(int j = 1;j<=i;j++){ System.out.print(j+"*"+i+"="+j*i+"\t"); } System.out.println(); } //////////////////////////////////////////// System.out.println(); for(int i = 1;i<=4;i++){ for(int j = 1;j<=4-i;j++){ System.out.print(" "); } for(int j = 1;j<=2*i-1;j++){ System.out.print("*"); } System.out.println(); } for(int i = 1;i<=3;i++){ java代码练习合集 for(int j = 1;j<=i;j++){ System.out.print(" "); } for(int j = 1;j<=7-2*i;j++){ System.out.print("*"); } System.out.println(); } } } public class Test13{ public static void main(String[] args) { //打印100以内的素数,所谓素数就是除了1和其本身外不在有别的约数的数。 //2 3 5 7 11 13........ boolean flag = true; for(int i = 2;i<100;i++){ flag = true; for(int j = 2;j100) return sum; else return 0; } } //导入java.util包中的Scanner类,放在第一条语句处 import java.util.Scanner; public class Test15 { public static void main(String[] args) { /* 1. 判断101-200之间有多少个素数,并输出所有素数。 2. 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。 3. 利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示, 60-89分之间的用B表示,60分以下的用C表示。 java代码练习合集 4. 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 5. 一球从100米高度自由落下,每次落地后反跳回原高度的一半; 再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高? //1 int count = 0; boolean flag = true; long start = System.currentTimeMillis(); for(int i = 1;i<20000;i++){ flag = true; for(int j = 2;j<(int)Math.sqrt(i);j++){ if(i%j==0){ flag = false; break; } } if(flag){ System.out.print(i+"\t"); count++; } } long end = System.currentTimeMillis(); System.out.println(); System.out.println("count ="+count); System.out.println(end-start); //4 Scanner sc = new Scanner(System.in); int letter = 0; int number = 0; int other = 0; int space = 0; System.out.println("请输入一组字符串"); String str = sc.nextLine();//输入一个字符串,输入结束的标志是回车 for(int i = 0;i='A'&&str.charAt(i)<='Z')||(str.charAt(i)>='a'&&str.charAt(i)<='z')){ letter++; } java代码练习合集 if(str.charAt(i)>='0'&&str.charAt(i)<='9'){ number++; } if(str.charAt(i)==' '){ space++; } } other = str.length()-letter-number-space; System.out.println("字母字符的个数是:"+letter); System.out.println("数字字符的个数是:"+number); System.out.println("空格字符的个数是:"+space); System.out.println("其他字符的个数是:"+other); //5 double d = 100; double h = 100; for(int i = 0;i<9;i++){ d=d+h; h/=2; System.out.println("d = "+d+" h = "+h); } System.out.println("d = "+d); System.out.println(" h = "+h/2); */ /* 6. 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元, 低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时, 高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时, 高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成, 从键盘输入当月利润I,求应发放奖金总数? */ Scanner sc = new Scanner(System.in); System.out.println("输入当月利润"); double income = sc.nextDouble(); double c = 0; java代码练习合集 if(income<=10){ c = cal_10(income); System.out.println(c); } else if(income>10&&income<=20){ c = cal_10_20(income); System.out.println(c); } else if(income>20&&income<=40){ c = cal_20_40(income); System.out.println(c); } else if(income>40&&income<=60){ } else if(income>60&&income<=100){ } else if(income>100){ } } public static double cal_10(double income){ return income*0.1; } public static double cal_10_20(double income){ return (income-10)*0.075+cal_10(10); } public static double cal_20_40(double income){ return (income-20)*0.05+cal_10_20(20); } public static double cal_40_60(double income){ return (income-40)*0.03+cal_20_40(40); } } 4. 面向对象: public class Rect { private int width; private int height; public Rect(){ this.width = 4; java代码练习合集 this.height = 5; } public Rect(int width){ this.width = width; this.height = 6; } public Rect(int width,int height){ this.width = width; this.height = height; } public int calculateArea(){ return this.width*this.height; } public int calPerimeter(){ return 2*this.width+2*this.height; } public static void main(String[] args) { Rect r = new Rect(2,3); System.out.println("area = "+r.calculateArea()); System.out.println("perimeter = "+r.calPerimeter()); } } public class Circle{ //定义数据成员: private double r; private final double PI = 3.14; public Circle(double r){ this.r = r; } public Circle(){ this.r = 5; } public double getR(){ return this.r; } public double area(){ return this.r*this.r*PI; } public double perimeter(){ return this.r*2*PI; } java代码练习合集 public void display(){ System.out.println("圆的半径为:"+this.r+",面积为:"+this.area()+",周长为:"+this.perimeter()); } } public class TestCircle{ public static void main(String[] args) { Circle c = new Circle(); c.display(); System.out.println("r = "+c.getR()); System.out.println("area = "+c.area()); System.out.println("perimeter = "+c.perimeter()); /////////////////////////// Circle c1 = new Circle(10); c1.display(); System.out.println("r = "+c1.getR()); System.out.println("area = "+c1.area()); System.out.println("perimeter = "+c1.perimeter()); new Circle().display(); } } public class Clock{ //定义数据成员 private int hour = 10; private int minute = 10; private int second = 10; //方法成员 /* 默认的构造方法: */ public Clock(){ this(5,6,7); } public Clock(int hour,int minute,int second){ this.hour = hour; this.minute = minute; java代码练习合集 this.second = second; } public Clock(int hour,int minute){ this.hour = hour; this.minute = minute; this.second = 20; } public Clock(int hour){ this.hour = hour; this.minute = 30; this.second = 50; } //设置时分秒的功能 public void setTime(int h,int m,int s){ this.hour = h; this.minute = m; this.second = s; } public void setHour(int hour){ this.hour = hour; } public void setMinute(int minute){ this.minute = minute; } public void setSecond(int second){ this.second = second; } //显示时间 public void showTime(){ System.out.println(this.hour+":"+this.minute+":"+this.second); } public void nextSecondTime(){ this.second++; if(this.second==60){ this.second = 0; this.minute++; if(this.minute==60){ this.minute = 0; this.hour++; } } this.hour%=24; } java代码练习合集 } public class TestClock { public static void main(String[] args) { //Clock c = new Clock(); //c.setTime(10,10,10); Clock c1 = new Clock(23,59,59); c1.showTime(); c1.nextSecondTime(); c1.showTime(); c1.nextSecondTime(); c1.showTime(); } } public class Point { private double x; private double y; public Point(double x,double y){ this.x = x; this.y = y; } public Point(){ } public static double dist(Point p1,Point p2){ double X = p1.x-p2.x; double Y = p1.y-p2.y; return Math.sqrt(X*X+Y*Y); } } public class TestPoint{ public static void main(String[] args) { Point p1 = new Point(0,0); Point p2 = new Point(3,4); double d =Point.dist(p1,p2); System.out.println("d = "+d); } } java代码练习合集 package cic.edu.cn.vo; public class Person{ private int pid; private String name; public Person(){} public Person(int pid,String name){ this.pid = pid; this.name = name; } //setter and getter方法 public int getPid(){ return this.pid; } public void setPid(int pid){ this.pid = pid; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } } import cic.edu.cn.vo.Person;//不能隔包导入 import java.util.*; public class TestPerson { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Person p = new Person(); p.setName("aaaa"); System.out.println(p.getName()); } } package cic.edu.cn.vo; public class Teacher{ public static int No = 1000; public int tid; public String password; protected String name; int age; java代码练习合集 public void finalize() throws Throwable{ super.finalize(); } public Teacher(){ this.tid = 1000; this.name = "zhanglaosan"; this.password = "123456"; this.age = 30; } } //package cic.edu.cn.vo; import cic.edu.cn.vo.Teacher; //import static java.lang.Math.PI; public class TestTeacher { static{ System.out.println("静态块代码被执行"); } { System.out.println("动态态块代码被执行"); } //求所有的输入参数的和并返回。 public int test(int...args){ int sum = 0; for(int i:args){ sum+=i; } return sum; } public static void main(String[] args){ TestTeacher tt = new TestTeacher(); //TestTeacher tt1 = new TestTeacher(); //double pi = Math.PI; int sum1 = tt.test(1,2,3,4,5); int sum2 = tt.test(1,2,3); int sum3 = tt.test(1,2); int sum4 = tt.test(); System.out.println("sum1 = "+sum1); System.out.println("sum2 = "+sum2); System.out.println("sum3 = "+sum3); System.out.println("sum4 = "+sum4); java代码练习合集 } } public class Animal //extends Object { public static void main(String[] args) { Animal animal = new Animal(); boolean flag = animal instanceof Animal;//如果左边的对象是右边的类的对象或者右边类的子类的对象返回true if(flag){ if(animal.getClass()==Animal.class){//getClass()方法是Object类中的方法,对象调用该方法返回对象的具体类型的封装类对象 System.out.println("animal是该类的实例"); } } } } public class Student { private int stuNo; private String stuName; private String sex; private int age; private String tel; public Student(int stuNo,String stuName,String sex,int age,String tel){ this.stuNo = stuNo; this.stuName = stuName; this.sex = sex; this.age = age; this.tel = tel; } public Student(){ } public Student(int stuNo,String stuName){ this.stuNo = stuNo; this.stuName = stuName; } public void display(){ System.out.println("编号是:"+this.stuNo+",姓名是:"+this.stuName+",性别是:"+this.sex); java代码练习合集 } public String toString(){ System.out.println("test........"); return "编号是:"+this.stuNo+",姓名是:"+this.stuName+",性别是:"+this.sex; } public static void main(String[] args) { Student stu = new Student(1000,"小王"); stu.display(); String str = stu+"-----"; System.out.println(stu); } } public class Singleton { /* 所谓的单例模式指使用该类的实例时都是同一个实例。 定义: (1)构造方法私有 (2)在类中定义一个私有的静态对象 (3)定义一个静态方法返回静态对象 */ private Singleton(){ } private static Singleton obj = new Singleton(); public static Singleton newInstance(){ return obj; } public static void main(String[] args) { Singleton s1 = Singleton.newInstance(); Singleton s2 = Singleton.newInstance(); Singleton s3 = Singleton.newInstance(); System.out.println(s1==s2&&s1==s3&&s2==s3); java代码练习合集 } } 数组: public class TestArray1{ public static void main(String[] args) { int [] arr = {1,2,3,4,5,6,7,8,9,10,11,34,456556,77,7,787,7,7,7,7,7,7,7,7,77,7,7}; int [] arr1 = {1,2,3,4,5,6,7,8,9,10}; int []arr2 = new int[]{1,2,3}; int max = arr[0]; int min = arr[0]; for(int i = 0;i=arr[i]) min = arr[i]; } System.out.println("min = "+min); System.out.println("max = "+max); for(int temp:arr1){ System.out.print(temp+" "); } System.out.println(); System.out.println("--------------------------------------"); int []arr3 = new int[20]; int value = 1; for(int i = 0;i=arr[i][j]) min = arr[i][j]; sum+=arr[i][j]; System.out.print(arr[i][j]+"\t"); } System.out.println(); System.out.println("sum = "+sum); System.out.println("avg = "+sum*1.0/arr[i].length); System.out.println("max = "+max); System.out.println("min = "+min); System.out.println(); } } java代码练习合集 } public class TestArray4 { public static void main(String[] args) { int [][]arr = {{1,2,3,4},{1,2},{1,2,3}}; int [][]arr1 = new int[3][]; arr1[0] = new int[3]; arr1[1] = new int[1]; arr1[2] = new int[3]; for(int i = 0;i5000){ this.grade = 2; }else{ this.grade = 3; } } @Override public void display() { // TODO Auto-generated method stub System.out.println(this); } @Override public String toString() { // TODO Auto-generated method stub return "销售员 "+this.name+"的编号是"+this.empno+",本月工资为"+this.salary+",工资级别是"+this.grade; } @Override java代码练习合集 public boolean equals(Object obj){ //判断参数对象是否为空 if(obj==null){ return false; } //判断调用对象和参数对象是否是同一对象 else if(this==obj){ return true; } //判断调用对象和参数对象是否是同一类型 else if(this.getClass()!=obj.getClass()){ return false; } Salesman s = (Salesman)obj; //判断具体属性值是否相等 return this.empno==s.empno&&this.name.equals(s.name)&&this.sales==s.sales&&this.commission==s.commission;//name.equals(name)调用String类中的equals } } package cic.edu.cn.vo; public class SalesManager extends Salesman { private double monthlyPay; public SalesManager() { // TODO Auto-generated constructor stub } public SalesManager(int empno,String name,double sales,double commission,double monthlyPay){ super(); this.empno = empno; this.name = name; this.sales = sales; this.commission = commission; this.monthlyPay = monthlyPay; this.salary = this.sales*this.commission+this.monthlyPay; if(this.salary<=5000){ this.grade = 1; }else if(this.salary<=8000&&this.salary>5000){ this.grade = 2; }else{ java代码练习合集 this.grade = 3; } } @Override public void display() { // TODO Auto-generated method stub System.out.println(this); } @Override public String toString() { // TODO Auto-generated method stub return "销售经理 "+this.name+"的编号是"+this.empno+",本月工资为"+this.salary+",工资级别是"+this.grade; } } package cic.edu.cn.vo; public class Technology extends Employee { private double hours; private double hourslyPay; public Technology() { // TODO Auto-generated constructor stub } public Technology(int empno,String name,double hours,double hourslyPay){ super(empno,name); this.hours = hours; this.hourslyPay = hourslyPay; this.salary = this.hours*this.hourslyPay; if(this.salary<=5000){ this.grade = 1; }else if(this.salary<=8000&&this.salary>5000){ this.grade = 2; }else{ this.grade = 3; } } public double getHours() { return hours; } public void setHours(double hours) { java代码练习合集 this.hours = hours; } public double getHourslyPay() { return hourslyPay; } public void setHourslyPay(double hourslyPay) { this.hourslyPay = hourslyPay; } @Override public void display() { // TODO Auto-generated method stub System.out.println(this); } /* @Override public void calculateSalary() { // TODO Auto-generated method stub this.salary = this.hours*this.hourslyPay; if(this.salary<=5000){ this.grade = 1; }else if(this.salary<=8000&&this.salary>5000){ this.grade = 2; }else{ this.grade = 3; } }*/ @Override public String toString() { // TODO Auto-generated method stub return "技术员 "+this.name+"的编号是"+this.empno+",本月工资为"+this.salary+",工资级别是"+this.grade; } } package cic.edu.cn.test; import cic.edu.cn.vo.Employee; import cic.edu.cn.vo.SalesManager; import cic.edu.cn.vo.Salesman; java代码练习合集 import cic.edu.cn.vo.Technology; public class Test { public static void showInfo(Employee e){ e.display(); } public static void main(String[] args) { // TODO Auto-generated method stub /* Employee e1 = new Technology(1000,"老李",100,200); Employee e2 = new Salesman(1001, "小张", 50000, 0.03); Employee e3 = new SalesManager(1002, "老王", 2000000, 0.003, 5000);*/ //Technology t1 = (Technology)t; //t.calculateSalary(); Employee emps[] ={ new Technology(1000,"老李",100,200), new Salesman(1001, "小张", 50000, 0.03), new SalesManager(1002, "老王", 2000000, 0.003, 5000) } ; for(Employee e:emps){ showInfo(e); } /*showInfo(e1); showInfo(e2); showInfo(e3);*/ Salesman s1 = new Salesman(1001, "小张", 50000, 0.03); Salesman s2 = new Salesman(1001, "小张", 50000, 0.03); System.out.println(s1.equals(s1)); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 接口:: package cic.edu.cn.inter; public interface Fire { public void fire(); } java代码练习合集 package cic.edu.cn.inter; public interface I1{ public void fun1(); public void fun2(); } package cic.edu.cn.inter; public interface I2{ public void fun3(); public void fun4(); } 实现类: package cic.edu.cn.inter.imp; import cic.edu.cn.inter.I1; import cic.edu.cn.inter.I2; public class A extends B implements I1, I2 { } package cic.edu.cn.inter.imp; public class B { public void fun1(){ } public void fun2(){ } public void fun3(){ } public void fun4(){ } } package cic.edu.cn.inter.imp; java代码练习合集 import cic.edu.cn.inter.Fire; public class Plane implements Fire{ @Override public void fire() { // TODO Auto-generated method stub System.out.println("Plane is firing.........."); } } package cic.edu.cn.inter.imp; import cic.edu.cn.inter.Fire; public class Tanke implements Fire { @Override public void fire() { // TODO Auto-generated method stub System.out.println("Tanke is firing........."); } } 测试类: package cic.edu.cn.test; import cic.edu.cn.inter.Fire; import cic.edu.cn.inter.imp.Plane; import cic.edu.cn.inter.imp.Tanke; public class Test { public static void test(Fire f){ f.fire(); } public static Fire newInstance(){ return new Plane(); java代码练习合集 } public static Fire newInstance1(){ return new Tanke(); } public static void main(String[] args) { // TODO Auto-generated method stub test(newInstance()); test(newInstance1()); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 反射: package ch8_1; import java.lang.reflect.Method; public class Test { private int i; public void test(){ System.out.println("aaaaaaaa"); } public Test(int i) { // TODO Auto-generated constructor stub this.i = i; } public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub /* Class c = new Test().getClass(); Method ms[] = c.getDeclaredMethods(); for(Method m:ms){ System.out.println(m.getModifiers()+" "+m.getName()); }*/ System.out.println(new Test()); java代码练习合集 System.out.println(new Long(System.currentTimeMillis()).doubleValue()/(1000*3600*24)/365); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 package ch8_2; public class A { public void fun()throws Exception{ } } class B extends A{ @Override public void fun(){ } } package ch8_2; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub int b = 2; Integer i = new Integer(2); //jdk1.4之前写法 if(i.equals(new Integer(2))){//封箱 int sum = b+i.intValue();//拆箱 } //jdk1.4后 if(i.equals(b)){ int sum = i+b; } System.out.println(i.doubleValue()); String age = "23"; java代码练习合集 int ageValue = Integer.parseInt(age); System.out.println(ageValue+1); } } package ch8_2; import java.util.Calendar; import java.util.Date; public class TestCalendar { public static void main(String[] args) { // TODO Auto-generated method stub Date d = new Date(1234567890123456L); Calendar c = Calendar.getInstance(); System.out.println(c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+ c.get(Calendar.DATE)+" "+c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)); System.out.println("--------------------------"); c.setTime(d); System.out.println("year = "+(d.getYear()+1900)); System.out.println("month = "+(d.getMonth()+1)); System.out.println("date = "+d.getDate()); System.out.println("--------------------------"); System.out.println(c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+ c.get(Calendar.DATE)+" "+c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)); } } package ch8_2; import java.util.Date; public class TestDate { public static void main(String[] args) { // TODO Auto-generated method stub Date d = new Date(); System.out.println("year = "+(d.getYear()+1900)); java代码练习合集 System.out.println("month = "+(d.getMonth()+1)); System.out.println("date = "+d.getDate()); Date d1 = new Date(System.currentTimeMillis());//格林威治时间 System.out.println("year = "+(d1.getYear()+1900)); System.out.println("month = "+(d1.getMonth()+1)); System.out.println("date = "+d1.getDate()); } } package ch8_2; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class TestSimpleDateFormat { public static void main(String[] args) { // TODO Auto-generated method stub Date date = new Date(); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String now1 = sdf1.format(date); System.out.println(now1); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String now2 = sdf2.format(date); System.out.println(now2); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss"); String now3 = sdf3.format(date); System.out.println(now3); //////////////////////解析////////////////////////// String strDate = "20121231010101"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); Date temp = null; try { temp = sdf.parse(strDate); } catch (ParseException e) { // TODO Auto-generated catch block java代码练习合集 e.printStackTrace(); } //打印年月日时分秒 Calendar c = Calendar.getInstance(); c.setTime(temp); System.out.println(c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+ c.get(Calendar.DATE)+" "+c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)); } } package ch8_3; public class Other { int m = 50; public void otherMethod(){ int a = 20; final int b = 30; class Inner{ public void innerMethod(){ System.out.println(b); System.out.println(m); } } Inner inner = new Inner(); inner.innerMethod(); } public static void main(String[] args) { // TODO Auto-generated method stub /*Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.innerMethod();*/ Other other = new Other(); other.otherMethod(); } } ————————————————————————————————————》》》》》》》》 package ch8_3; java代码练习合集 public class Outer { private int a = 6; public void initA(int a){ this.a = a; } public class Inner{ private int a = 20; public void innerMethod(){ System.out.println("inner a = "+a); System.out.println("outer a = "+Outer.this.a); } } public void outerMethod(){ //创建外部类对象 Outer outer = new Outer(); //创建内部类对象 Outer.Inner inner = outer.new Inner(); //通过内部类对象调用内部类中的成员方法 inner.innerMethod(); } public static void outerStaticMethod(){ Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.innerMethod(); } public static void main(String[] args) { Outer outer = new Outer(); outer.outerMethod(); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 内部类:匿名类: package ch8_4; public class A { int a = 30; static int b = 50; public static class Inner{ public static void innerFun(){ System.out.println(b); } java代码练习合集 } public void fun1( B b){ b.fun(); } public void fun2(Fire f){ f.fire(); } public static void main(String[] args) { A.Inner inner = new A.Inner(); A.Inner.innerFun(); /*A a = new A(); //new B(){}表示创建一个B的无名子类对象 a.fun1(new B(){ @Override public void fun1() { // TODO Auto-generated method stub System.out.println("fun1被调用。。。。。。。"); } }); a.fun2(new Fire(){ @Override public void fire() { // TODO Auto-generated method stub System.out.println("fire方法被调用"); } });*/ Fire f = new Fire(){ @Override public void fire() { // TODO Auto-generated method stub System.out.println("fire............"); } java代码练习合集 }; f.fire(); } } package ch8_4; public abstract class B { public abstract void fun1(); public void fun(){ System.out.println("B的fun方法被调用"); } } package ch8_4; public interface Fire { public void fire(); } ——————————————————————————》》》》》》》》》》》》》》》》》》》》》》》》》 异常: package ch9_1; import java.io.IOException; public class Test1 { public void fun(int i){ try{ if(i==0){ throw new Exception(); } }catch(Exception e){ e.printStackTrace(); } } public void fun1(int i)throws Exception,IOException{ if(i==0){ throw new Exception(); } } public static void main(String[] args) throws IOException, Exception { // TODO Auto-generated method stub java代码练习合集 /*try{ int b = 40-5; System.out.println(b); int a = 5/0; System.out.println(a); if(a==5) return; System.out.println("aaaaaaaaaaaaa"); }catch(NullPointerException e){ e.printStackTrace(); } catch(ArithmeticException e){ System.out.println("除数不允许为0"); e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ System.out.println("finally 块代码被执行。。。。。。。。。"); } System.out.println("bbbbbbbbb");*/ Test1 t = new Test1(); t.fun(0); t.fun1(9); } } 《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《》》》》》》》》》》》》》》》》》》》》》》》》》》 线程: package ch10_1; public class MyThread extends Thread { public MyThread(String name) { // TODO Auto-generated constructor stub super(name); } @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i<10;i++){ java代码练习合集 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("My Thead run方法被执行------"+i); } } } package ch10_1; public class MyThread2 extends Thread { @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i<10;i++){ System.out.println("My Thead run方法被执行------"+i+Thread.currentThread().getName()); } } } package ch10_1; public class MyThreadTest { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub //定义了一个线程对象 MyThread mt = new MyThread("aaa");//新建态 //mt.stop(); MyThread2 mt1 = new MyThread2();//新建态 mt.setPriority(10); mt1.setPriority(5); mt.start(); //mt.stop(); // mt1.start(); java代码练习合集 mt.join(); System.out.println("active count = "+Thread.activeCount()); System.out.println(mt.getName()+" "+mt1.getName()+" "+Thread.currentThread().getName()); for(int i = 0;i<10;i++){ System.out.println("main方法被执行:"+i); } } } 单线程: package ch10_1; public class SingleThread { public void run(){ for(int i = 0;i<10;i++){ System.out.println("run方法被执行:"+i); } } public static void main(String[] args) { // TODO Auto-generated method stub for(int i = 0;i<10;i++){ System.out.println("main方法被执行:"+i); } new SingleThread().run(); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 线程: package ch10_2; public class MainThread { public static void main(String[] args) { // TODO Auto-generated method stub MyThread1 mt1 = new MyThread1(); java代码练习合集 MyThread2 mt2 = new MyThread2(); Thread t = new Thread(mt2); mt1.start(); t.start(); new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub } }).start(); } } package ch10_2; public class MyThread1 extends Thread { @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i<10;i++){ System.out.println("my thread1 ----"+i); } } } package ch10_2; public class MyThread2 implements Runnable { @Override public void run() { // TODO Auto-generated method stub for(int i = 0;i<10;i++){ System.out.println("my thread2 ----"+i); } } } java代码练习合集 《》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 龟兔赛跑: package ch10_3; public class Rabbit extends Thread { @Override public void run() { // TODO Auto-generated method stub for(int i = 100;i<=1000;i+=100){ try { Thread.sleep(1000); System.out.println("兔子跑了"+i+"米"); if(i==900){ System.out.println("兔子开始睡觉......."); this.suspend(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package ch10_3; public class Tortoise implements Runnable { private Rabbit rabbit; public Tortoise(Rabbit rabbit) { // TODO Auto-generated constructor stub this.rabbit = rabbit; } @Override public void run() { // TODO Auto-generated method stub for(int i = 50;i<=1000;i+=50){ try { Thread.sleep(1000); System.out.println("乌龟跑了"+i+"米"); } catch (InterruptedException e) { java代码练习合集 // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("乌龟先到终点,乌龟获得了比赛的胜利"); rabbit.resume(); } } package ch10_3; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Rabbit rabbit = new Rabbit(); Tortoise tortoise = new Tortoise(rabbit); new Thread(tortoise).start(); rabbit.start(); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 package ch10_3; import java.awt.*; import java.awt.event.*; public class TextTest extends Frame implements Runnable,ActionListener{ Panel p1,p2; Label testLabel,timeLabel,scoreLabel; TextArea ta; Button startButton; int i = 10; public TextTest(){ p1 = new Panel(); p2 = new Panel(); p1.setLayout(new GridLayout(2,1)); p2.setLayout(new GridLayout(2,1)); testLabel = new Label("测字软件",Label.CENTER); timeLabel = new Label("剩余时间: "+10+" 秒"); scoreLabel = new Label("成绩: ? 字/分"); java代码练习合集 startButton = new Button("开始"); ta = new TextArea(30,50); ta.setEditable(false); p1.add(testLabel); p1.add(timeLabel); p2.add(scoreLabel); p2.add(startButton); add(p1,BorderLayout.NORTH); add(ta); add(p2,BorderLayout.SOUTH); setTitle("测字软件"); setSize(300,400); setVisible(true); startButton.addActionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } public void actionPerformed(ActionEvent e){ ta.setText(""); ta.setEditable(true); ta.requestFocus(); Thread x = new Thread(TextTest.this); x.start(); } public void run(){ for(i = 10; i>0;i--){ timeLabel.setText("剩余时间: "+i+" 秒"); startButton.removeActionListener(this); try{ Thread.sleep(1000); } catch(InterruptedException e){ e.printStackTrace(); } } java代码练习合集 ta.setEditable(false); scoreLabel.setText("成绩: "+ta.getText().length()*6+" 字/分"); startButton.addActionListener(this); } public static void main(String args[]){ new TextTest(); } }》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 文件: package ch11_1; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class FileTest { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println(File.pathSeparator); System.out.println(File.separator); File f1 = new File("d:\\javacode\\a"); File f2 = new File(f1,"a.txt"); System.out.println("canExecute:"+f2.canExecute()); System.out.println("canRead:"+f2.canRead()); System.out.println("canWrite:"+f2.canWrite()); System.out.println("is exitis:"+f2.exists()); /*if(!f2.exists()){ if(f2.createNewFile()){ System.out.println("创建成功"); }else{ System.out.println("创建失败"); } }*/ if(f1.delete()){ System.out.println("删除成功"); }else{ System.out.println("删除失败"); } java代码练习合集 File f3 = new File("d:\\javacode\\ch4\\c.txt"); System.out.println(f2.compareTo(f3)); System.out.println(f3.getAbsolutePath()); System.out.println(f3.getName()); System.out.println(f3.getParent()); System.out.println(f3.getPath()); File f4 = new File("d:\\javacode\\a.txt"); if(f4.isDirectory()){ System.out.println("是目录"); } if(f4.isFile()&&f4.delete()){ System.out.println(f4.getName()+"删除成功"); } Date date = new Date(f4.lastModified()); System.out.println(new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss").format(date)); String []files = new File("d:\\javacode\\ch5").list(); //打印该目录中的java源文件 System.out.println("------------------"); for(String file :files){ File f = new File(new File("d:\\javacode\\ch5"),file); if(file.endsWith("java")&&f.isFile()) System.out.println(file); } System.out.println("-------------------"); File []fs = new File("d:\\javacode\\ch5").listFiles(); for(File f:fs){ if(f.getName().endsWith(".java")&&f.isFile()){ System.out.println(f.getName()); } } System.out.println("----------------------"); File fs1[] = new File("d:\\javacode\\ch5").listFiles(new FileFilter() { private int i = 0; @Override public boolean accept(File file) { // TODO Auto-generated method stub System.out.println(i++); return file.isFile()&&file.getName().endsWith(".java"); java代码练习合集 } }); for(File temp:fs1){ System.out.println(temp.getName()); } System.out.println("----------------------"); File fs2[] = new File("d:\\javacode\\ch5").listFiles(new FilenameFilter() { private int i = 0; @Override public boolean accept(File file,String name) { // TODO Auto-generated method stub return new File(file,name).isFile()&&name.endsWith(".java"); } }); for(File temp:fs2){ System.out.println(temp.getName()); } System.out.println("-----------------------------"); System.out.println( new File("d:\\javacode\\ch5").toURI()); } } package ch11_2; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileInputStreamTest { public static void main(String[] args) { // TODO Auto-generated method stub FileInputStream fis1 = null; FileInputStream fis2 = null; BufferedInputStream bfis = null; java代码练习合集 try { fis1 = new FileInputStream(new File("d:\\javacode\\ch5\\Emp.java")); bfis = new BufferedInputStream(fis1); int i = -1; while((i = bfis.read())!=-1){ System.out.print((char)i); } System.out.println(); System.out.println("-----------------------------------------------------"); ////////////////////////////////////////////// fis2 = new FileInputStream("d:\\javacode\\ch5\\Emp.java"); byte[]b = new byte[fis2.available()]; fis2.read(b); System.out.println(new String(b)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fis1!=null){ try { fis1.close(); fis2.close(); bfis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } package ch11_2; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; java代码练习合集 import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class FileOutputStreamTest { public static void main(String[] args) { // TODO Auto-generated method stub Date date = new Date(System.currentTimeMillis()); String name = new SimpleDateFormat("yyyyMMddHHmmss").format(date)+".txt"; String content = new SimpleDateFormat("yyyy'年'MM'月'dd'日'HH'时'mm'分'ss'秒'").format(date); FileOutputStream fos = null; BufferedOutputStream bfos = null; try { fos = new FileOutputStream(name); bfos = new BufferedOutputStream(fos); bfos.write(content.getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fos!=null){ try { bfos.flush(); bfos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 序列化问题: package ch11_3; java代码练习合集 import java.io.Serializable; public class Emp implements Serializable{//实现该接口的类的对象允许被序列化 /** * */ public Emp() { // TODO Auto-generated constructor stub } private static final long serialVersionUID = 1L; private transient int empno; private String ename; private int age; public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } package ch11_3; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Test { java代码练习合集 public static void main(String[] args) { // TODO Auto-generated method stub FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream("d:\\emp.ser"); oos = new ObjectOutputStream(fos); Emp e = new Emp(); e.setEmpno(1000); e.setEname("zhangsan"); e.setAge(20); Emp e1 = new Emp(); e1.setEmpno(1001); e1.setEname("lisi"); e1.setAge(22); Emp emps[] = {e,e1}; oos.writeObject(emps); //oos.writeObject(e1); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(fos!=null){ fos.close(); } if(oos!=null){ oos.flush(); oos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } java代码练习合集 } package ch11_3; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; public class Test1 { public static void main(String[] args) { // TODO Auto-generated method stub FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream("d:\\emp.ser"); ois = new ObjectInputStream(fis); /*Emp e = null; while((e = (Emp)ois.readObject())!=null){ System.out.println(e.getEname()+" "+e.getEmpno()+" "+e.getAge()); if(e.getAge()==22){ break; } }*/ Object obj = ois.readObject(); Emp emps[] = (Emp[])obj; for(Emp e:emps){ System.out.println(e.getEname()+" "+e.getEmpno()+" "+e.getAge()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block java代码练习合集 e.printStackTrace(); }finally{ try { if(fis!=null){ fis.close(); } if(ois!=null){ ois.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 package cic.edu.cn.vo; import java.io.Serializable; public class Student implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String stuid; private String stuname; private int age; private int score; public String getStuid() { return stuid; } public void setStuid(String stuid) { this.stuid = stuid; } public String getStuname() { return stuname; } java代码练习合集 public void setStuname(String stuname) { this.stuname = stuname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @Override public String toString() { // TODO Auto-generated method stub return this.stuid+" "+this.stuname+" "+this.age+" "+this.score; } } package cic.edu.cn.operator; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Scanner; import cic.edu.cn.vo.Student; public class OperatorStudent { public static void writeStudent(Object obj,ObjectOutputStream oos){ } public static Object readStudent(ObjectInputStream ois){ return null; } java代码练习合集 public static void writeStudent(Object obj,FileOutputStream os){ } public static Object readStudent(FileInputStream fis){ return null; } public static Student[] inputStudentInfo() throws IOException,FileNotFoundException{ Scanner sc = new Scanner(System.in); //标准输入;输入字节流 //BufferedInputStream bis = new BufferedInputStream(System.in); StringBuffer sb = new StringBuffer(); int i ; int i1 = 0; int count = 0; while(true){ System.out.println("输入您的选择"); 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 : 退出系统 *"); System.out.println("**********************"); i = sc.nextInt(); //System.out.println("i = "+i); if(i==1){ while(true){ System.out.println("**********************"); System.out.println("* 1 : 输入学生信息 *"); System.out.println("* 0 : 停止输入 *"); System.out.println("**********************"); System.out.println("输入你的选择:"); i1 = sc.nextInt(); if(i1==1){ count++; System.out.println("输入学生编号:"); int stuid = sc.nextInt(); System.out.println("输入学生姓名:"); String stuname = sc.next(); System.out.println("输入学生年龄:"); int age = sc.nextInt(); java代码练习合集 System.out.println("输入学生成绩:"); int score = sc.nextInt(); String info = stuid+","+stuname+","+age+","+score; sb.append(info+"\n"); }else if(i1==0){ break; } } }else if(i==2){ }else if(i==3){ }else if(i==4){ }else if(i==5){ }else if(i==6){ }else if(i==0){ break; } } Student [] stus = new Student[count]; System.out.println(sb); String[] stuInfos = sb.toString().split("\n"); for(int m = 0;m { private E p1; private E p2; public E getP1() { return p1; } public void setP1(E p1) { java代码练习合集 this.p1 = p1; } public E getP2() { return p2; } public void setP2(E p2) { this.p2 = p2; } public String add(){ return p1+" "+p2; } } package ch12_1; public class GenericGroup { private int size; private E[]objs; private void init(){ this.size = 0; this.objs = (E[]) new Object[10]; } public GenericGroup() { // TODO Auto-generated constructor stub init(); } public void clear(){ init(); } public void add(E obj){ if(this.size==this.objs.length){ Object[]temp = this.objs; this.objs = (E[]) new Object[this.objs.length*2]; System.arraycopy(temp, 0, this.objs, 0, temp.length); } this.objs[size] = obj; this.size++; } public int getSize(){ return this.size; } public E get(int index){ return this.objs[index]; java代码练习合集 } } package ch12_1; public class ObjectGroup { private int size; private Object[]objs; private void init(){ this.size = 0; this.objs = new Object[10]; } public ObjectGroup() { // TODO Auto-generated constructor stub init(); } public void clear(){ init(); } public void add(Object obj){ if(this.size==this.objs.length){ Object[]temp = this.objs; this.objs = new Object[this.objs.length*2]; System.arraycopy(temp, 0, this.objs, 0, temp.length); } this.objs[size] = obj; this.size++; } public int getSize(){ return this.size; } public Object get(int index){ return this.objs[index]; } } package ch12_1; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Calculate c1 = new Calculate(); java代码练习合集 /* * public class Calculate { private Integer p1; private Integer p2; public Integer getP1() { return p1; } public void setP1(Integer p1) { this.p1 = p1; } public Integer getP2() { return p2; } public void setP2(Integer p2) { this.p2 = p2; } public String add(){ return p1+" "+p2; } } * * * */ c1.setP1(2); c1.setP2(1); System.out.println(c1.add()); Calculate c2 = new Calculate(); c2.setP1("aa"); c2.setP2("bb"); System.out.println(c2.add()); /* * public class Calculate { private String p1; private String p2; public String getP1() { return p1; } public void setP1(String p1) { this.p1 = p1; java代码练习合集 } public String getP2() { return p2; } public void setP2(String p2) { this.p2 = p2; } public String add(){ return p1+" "+p2; } } * * */ } } package ch12_1; public class Test1 { public static void main(String[] args) { // TODO Auto-generated method stub ObjectGroup og = new ObjectGroup(); og.add(1); og.add(1); og.add(1); og.add("aaa"); int sum = 0; for(int i = 0;igg = new GenericGroup(); gg.add(1); gg.add(1); gg.add(1); int sum = 0; for(int i = 0;i{ public T get(){ return null; } public E getzzxz(){ return null; } public static void main(String[] args) { A aa = new A(); } } package ch12_2; public interface Compare { public int compareTo(E e); } java代码练习合集 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 package ch12_2; public class Dog { private int age; private int weight; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } } package ch12_2; public class Person implements Compare{ private int age; private String name; private Dog dog; 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; } @Override public int compareTo(Person e) { // TODO Auto-generated method stub if(this.age!=e.age){ return this.age-e.age; } java代码练习合集 return this.name.compareTo(e.name); } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 集合框架: package ch13_1; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class ArrayListTest { public static void main(String[] args) { // TODO Auto-generated method stub List arrayList = new ArrayList(); arrayList.add(new Employee(1000,"zhangsan",new Date(),"salesman")); arrayList.add(new Employee(1001,"lisi",new Date(),"salesman")); arrayList.add(new Employee(1002,"wangwu",new Date(),"salesman")); arrayList.add(new Employee(1003,"zhaoliu",new Date(),"salesman")); //增强的for循环遍历 for(Employee e:arrayList){ System.out.println(e); } System.out.println("-------------"); Iteratorit = arrayList.iterator(); while(it.hasNext()){ System.out.println(it.next()); } System.out.println("------------------"); ListIterator lit = arrayList.listIterator(); while(lit.hasNext()){ System.out.println(lit.next()); } System.out.println("--------------------------"); while(lit.hasPrevious()){ System.out.println(lit.previous()); java代码练习合集 } } } package ch13_1; import java.text.SimpleDateFormat; import java.util.Date; public class Employee implements Comparable { private int empno; private String ename; private Date hiredate; private String job; public Employee() { // TODO Auto-generated constructor stub } public Employee(int empno, String ename, Date hiredate, String job) { super(); this.empno = empno; this.ename = ename; this.hiredate = hiredate; this.job = job; } public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } java代码练习合集 public String getJob() { return job; } public void setJob(String job) { this.job = job; } @Override public String toString() { // TODO Auto-generated method stub return this.empno+" "+this.ename+" "+this.job+" "+new SimpleDateFormat("yyyy-MM-dd").format(this.hiredate); } @Override public int compareTo(Employee o) { // TODO Auto-generated method stub if(!this.ename.equals(o.ename)){ return o.ename.compareTo(this.ename); } return o.hiredate.compareTo(this.hiredate); } } package ch13_1; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class HashMapTest { public static void main(String[] args) { // TODO Auto-generated method stub Map map1 = new HashMap(); map1.put("a", 97); map1.put("b", 98); map1.put("c", 99); map1.put("d", 100); Set> en = map1.entrySet(); Iterator> it = en.iterator(); while(it.hasNext()){ Map.Entry entry = it.next(); java代码练习合集 System.out.println(entry.getKey()+"----"+entry.getValue()); } ////////////////////////////////////////////////////////////////////////////// System.out.println("------------------"); Set keys = map1.keySet(); Iterator it1 = keys.iterator(); while(it1.hasNext()){ String key = it1.next(); Integer value = map1.get(key); System.out.println(key+"<----------->"+value); } } } package ch13_1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class PropertiesTest { public static void main(String[] args) throws FileNotFoundException, IOException { // TODO Auto-generated method stub Properties p = new Properties(); /*p.setProperty("username", "scott"); p.setProperty("password", "tiger"); p.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl"); p.store(new FileOutputStream("d:\\jdbc.properties"), "oracle connectivity info");*/ p.load(new FileInputStream("jdbc.properties")); String username = p.getProperty("username"); String password = p.getProperty("password"); String url = p.getProperty("url"); System.out.println(username+" "+password+" "+url); } } package ch13_1; java代码练习合集 import java.util.Date; import java.util.Iterator; import java.util.Stack; public class StackTest { public static void main(String[] args) { // TODO Auto-generated method stub Stack stack = new Stack(); stack.push(new Employee(1000, "zhangsan", new Date(), "manager")); stack.push(new Employee(1001, "zhangsan", new Date(), "manager")); stack.push(new Employee(1002, "zhangsan", new Date(), "manager")); //Iterator it = stack.iterator(); while(!stack.empty()){ System.out.println(stack.pop()); } } } package ch13_1; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { // TODO Auto-generated method stub Map map1 = new TreeMap(new Comparator() { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub return o2.compareTo(o1); } }); map1.put("a", 1); java代码练习合集 map1.put("c", 2); map1.put("b", 3); map1.put("d", 4); Set keys = map1.keySet();//获取键的Set集合,通过map的get(key)获得值 for(String key:keys){ Integer value = map1.get(key); System.out.println(key+"----------"+value); } } } package ch13_1; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { // TODO Auto-generated method stub Set sets1 = new TreeSet(); sets1.add("eee"); sets1.add("bbb"); sets1.add("ccc"); sets1.add("aaa"); //增强的for循环遍历 for(String str:sets1){ System.out.println(str); } Iterator it = sets1.iterator(); while(it.hasNext()){ System.out.println(it.next()); } ////////////////////////////////// Set sets2 = new TreeSet(); sets2.add(new Employee(1000, "zhangxiaosan", new Date(System.currentTimeMillis()), "aaaa")); java代码练习合集 sets2.add(new Employee(1001, "zhangdasan", new Date(System.currentTimeMillis()), "aaaa")); sets2.add(new Employee(1002, "zhanglaosan", new Date(System.currentTimeMillis()), "aaaa")); for(Employee e:sets2){ System.out.println(e); } /////////////////////////////////////// TreeSet sets3 = new TreeSet(new Student()); sets3.add(new Student(1,"aaa")); sets3.add(new Student(20,"aaa")); sets3.add(new Student(15,"aaa")); for(Student s:sets3){ System.out.println(s.getStuage()+" "+s.getStuname()); } TreeSet sets4 = new TreeSet(new Comparator(){ @Override public int compare(Teacher o1, Teacher o2) { // TODO Auto-generated method stub if(o1.getTage()!=o2.getTage()) return o2.getTage()-o1.getTage(); return o1.getTname().compareTo(o2.getTname()); } }); sets4.add(new Teacher(20,"mmm")); sets4.add(new Teacher(43,"aaa")); sets4.add(new Teacher(20,"bbb")); for(Teacher t:sets4){ System.out.println(t.getTage()+"------"+t.getTname()); } } } 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《 java代码练习合集

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 8 金币 [ 分享文档获得金币 ] 2 人已下载

下载文档