zhiyinjixu

  博客园  :: 首页  ::  :: 联系 ::  :: 管理

Java程序设计基础例题

//app2_1.java 简单的java应用程序
public class app2_1 //定义app2_1类
{
public static void main(String[] args) //定义主方法
{
System.out.println("Hello Java !");
}
}


//App2_2.java Java小程序
import java.awt.*; //加载java.awt类库中的所有类
import java.applet.*; //加载java.applet类库中的所有类
public class App2_2 extends Applet //定义类App2_2,其父类为Applet
{
public void paint(Graphics g)
{
g.drawString("Hello Java!",50,50);
}
}

<App2_2.htm>
<html>
<APPLET code="App2_2.class"
width="200"
height="120"
alt="很抱歉,您的浏览器不支持Java applet。">
</APPLET>
</html>

//app3_1.java 类型自动转换
public class app3_1 //定义类app3_1
{
public static void main(String[] args)
{
int a=155;
float b=21.0f;
System.out.println("a="+a+",b="+b); //输出a,b的值
System.out.println("a/b="+(a/b)); //输出a/b的值
}
}


//app3_2.java 整数与浮点数的类型转换
public class app3_2
{
public static void main(String[] args)
{
int a=155;
int b=9;
float g,h;
System.out.println("a="+a+",b="+b); //输出a,b的值
g=a/b; //将a除以b的结果放在g中
System.out.println("a/b="+g+"\n"); //输出g的值
System.out.println("a="+a+",b="+b); //输出a,b的值
h=(float)a/b; //先将a强制转换成float类型后再参加运算
System.out.println("a/b="+h); //输出h的值
}
}

//app3_3.java 由键盘输入字符串
import java.io.*; //加载java.io类库里的所有类
public class app3_3
{
public static void main(String[] args) throws IOException
{
BufferedReader buf;
String str;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入字符串;");
str=buf.readLine(); //将输入的文字指定给字符串变量str存放
System.out.println("您输入的字符串是:"+str); //输出字符串
}
}

//app3_4.java 由键盘输入整数
import java.io.*;
public class app3_4
{
public static void main(String[] args) throws IOException
{
float num;
String str;
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入一个实数:");
str=buf.readLine(); //将输入的文字指定给字符串变量str存放
num= Float.parseFloat(str); //将str转换成float类型后赋给num
System.out.println("您输入的数为:"+num);
}
}

//app3_5.java 由键盘输入多个数据
import java.io.*;
public class app3_5
{
public static void main(String[] args) throws IOException
{
int num1,num2;
String str1,str2;
InputStreamReader in;
in= new InputStreamReader(System.in);
BufferedReader buf;
buf=new BufferedReader(in);
System.out.print("请输入第一个数:");
str1=buf.readLine(); //将输入的内容赋值给字符串变量str1
num1=Integer.parseInt(str1); //将str1转成int类型后赋给num1
System.out.print("请输入第二个数:");
str2=buf.readLine(); //将输入的内容赋值给字符串变量str2
num2=Integer.parseInt(str2); //将str2转成int类型后赋给num2
System.out.println(num1+"*"+num2+"="+(num1*num2));
}
}

//app3_6.java 由键盘输入多个数据
import java.util.*; //加载java.util类库里的所有类
public class app3_6
{
public static void main(String[] args)
{
int num1;
double num2;
Scanner reader=new Scanner(System.in);
System.out.print("请输入第一个数:");
num1= reader.nextInt(); //将输入的内容做int型数据赋值给变量num1
System.out.print("请输入第二个数:");
num2= reader.nextDouble(); //将输入的内容做double型数据赋值给变量num2
System.out.println(num1+"*"+num2+"="+(num1*num2));
}
}

//app3_7.java 由键盘输入多个数据
import java.util.*; //加载java.util类库里的所有类
public class app3_7
{
public static void main(String[] args)
{
String s1,s2;
Scanner reader=new Scanner(System.in);
System.out.print("请输入第一个数:");
s1= reader.nextLine(); //将输入的内容做为字符型数据赋值给变量s1
System.out.print("请输入第二个数:");
s2= reader.next(); //按Enter键时next()方法将回车符和换行符
System.out.println("输入的是"+s1+"和"+s2);
}
}

//app3_8.java 关系运算符和逻辑运算符的使用
public class app3_8
{
public static void main(String[] args)
{
int a=25,b=7;
boolean x=a<b; //x=false
System.out.println("a<b="+x);
int e=3;
boolean y= a/e>5; //y=true
System.out.println("x^y="+(x^y));
if(e!=0 & b<0) System.out.println("b/0="+b/0);
else System.out.println("a%e="+a%e);
int f=0;
if(f!=0 && a/f>5) System.out.println("a/f="+a/f);
else System.out.println("f="+f);
}
}

//app4_1.java if语句的应用
public class app4_1
{
public static void main(String[] args)
{
int a=1,b=2,c=3,max,min;
if(a>b)
max=a;
else
max=b;
if(c>max) max=c;
System.out.println("Max="+max);
min=a<b ? a : b;
min=c<min ? c : min;
System.out.println("Min="+min);
}
}

//app4_2.java 多重条件选择语句的应用
public class app4_2
{
public static void main(String[] args)
{
int testscore=86;
char grade;
if(testscore>=90) {
grade='A';
} else if (testscore>=80) {
grade='B';
} else if (testscore>=70) {
grade='C';
} else if (testscore>=60) {
grade='D';
} else {
grade='E';
}
System.out.println("评定成绩为:"+ grade);
}
}

// app4_3.java switch语句的应用
public class app4_3
{
public static void main (String[] args) throws Exception
{
int a=100, b=6;
char oper;
System.out.print("请输入运算符:");
oper=(char)System.in.read(); //从键盘读入一个字符存入变量oper中
switch (oper)
{
case '+': // 输出a+b
System.out.println(a+"+"+b+"="+(a+b));
break;
case '-': // 输出a-b
System.out.println(a+"-"+b+"="+(a-b));
break;
case '*': // 输出a*b
System.out.println(a+"*"+b+"="+(a*b));
break;
case '/': // 输出a/b
System.out.println(a+"/"+b+"="+((float)a/b));
break;
default: // 输出字符串
System.out.println("输入的符号不正确!");
}
}
}

// app4_4.java switch语句的应用
import java.util.*;
public class app4_4
{
public static void main (String[] args)
{
int month,days;
Scanner reader =new Scanner(System.in);
System.out.print("请输入月份:");
month=reader.nextInt();
switch (month)
{
case 2: days=28; //2月份是28天
break;
case 4:
case 6:
case 9:
case 11: days=30; //4、6、9、11月份的天数为30
break;
default: days=31; // 其它月份为31天
}
System.out.println(month+"月份为【"+days+"】天");
}
}

// app4_5.java while语句的应用
public class app4_5
{
public static void main (String[] args)
{
final int MAX=15; //定义常量MAX=15
int i=0,j=1,k=1;
while(k<=MAX)
{
System.out.print (" "+i+" "+j);
i=i+j; //计算Fibonacci序列中的下一个数
j=i+j; //计算Fibonacci序列中的下一个数
k=k+2; //用于改变循环的条件表达式的值
}
System.out.println();
}
}

//app4_6.java while语句的应用
import java.io.*;
public class app4_6
{
public static void main(String[] args) throws IOException
{
int a=0,b=1,n,num;
String str;
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入一个正整数:");
str=buf.readLine(); //从键盘上读入字符串赋给变量str
num= Integer.parseInt (str); //将str转换成int类型后赋给num
while (b<num)
{
n=a+b;
a=b;
b=n;
}
if (num==b) System.out.println(num+"是Fibonacci数");
else System.out.println(num+"不是Fibonacci数");
}
}

//app4_7.java hasNextXXX()方法的使用
import java.util.*;
public class app4_7
{
public static void main(String[] args)
{
double sum=0;
int n=0;
System.out.println("请输入多个数,每输入一个数后按Enter或Tab或空格键确认:");
System.out.println("最后输入一个非数字结束输入操作");
Scanner reader=new Scanner(System.in); //用System.in创建一个Scanner对象
while(reader.hasNextDouble() ) //判断是否输入了双精度浮点型数据
{
double x=reader.nextDouble(); //读取并转换表示double型数据的字符序列
sum=sum+x;
n++;
}
System.out.print("共输入了【"+n+"】个数,其和为:"+sum);
}
}

// app4_8.java do-while循环的应用
import java.util.*;
public class app4_8
{
public static void main(String[] args)
{
int n,i=1,sum=0;
Scanner buf=new Scanner(System.in);
do{
System.out.print("输入正整数:");
n=buf.nextInt();
} while (n<=0); //要求输入数n必须大于0,否则一直要求重复输入
while(i<=n)
sum+=i++; //计算和
System.out.println("1+2+…+"+n+"="+sum); //输出结果
}
}

// app4_9.java
import java.io.*;
public class app4_9
{
public static void main(String[] args) throws IOException
{
int a,b,k;
String str1,str2;
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入第一个数 a=");
str1=buf.readLine(); //将输入的文字赋值给字符串变量str1
a=Integer.parseInt(str1); //将str1转成int类型后赋给a
System.out.print("请输入第二个数 b=");
str2=buf.readLine(); //将输入的文字赋值给字符串变量str2
b=Integer.parseInt(str2); //将str2转成int类型后赋给b
System.out.print("gcd("+a+","+b+")=");
do {
k=a % b;
a=b;
b=k;
}while(k!=0); //若余数k不为0,则继续进行下一次循环
System.out.println(a);
}
}

//app4_10.java 循环语句的应用
import java.util.*;
public class app4_10
{
public static void main(String[] args)
{
int n=1,s=1,m;
Scanner reader=new Scanner(System.in);
do {
System.out.print("请输入大于1的整数m:");
m=reader.nextInt();
} while (m<=1); //当m≤1会一直要求重复输入,直到m>1为止
while (s<m) // 判断n!<m是否成立
{
s*=n; //计算s=n!
n++;
}
System.out.println("s="+s/(n-1)+" n="+(n-2)); //输出结果
}
}

//app4_11.java for循环语句的应用
public class app4_11
{
public static void main(String[] args)
{
int i,n=10,s=0;
for(i=1;i<=n;i++) //从1到10进行累加求和
s=s+i;
System.out.println("Sum=1+……+"+n+"="+s);
s=0;
System.out.print ("Sum=");
for(i=n;i>1;i--) //从10到1进行累加求和
{
s+=i;
System.out.print (i+"+"); //输出数i和加号“+”
}
System.out.println(i+"="+(s+i)); //输出结果
}
}

//app4_12.java 循环嵌套的应用
public class app4_12
{
public static void main(String[] args)
{
final int MAX=100; //定义常量MAX=100
int j,k,n;
System.out.println("2~"+MAX+"之间的所有素数为:");
System.out.print("2\t"); //2是第一个素数,不需测试直接输出
n=1; //n累计素数的个数
k=3; //k是被测试的数,从最小奇数3开始测试,所有偶数不需测试
do //外层循环,从3到100进行素数测试
{
j=3; //用j去除待测试的数
while(j<Math.sqrt(k) && (k % j!=0)) //内层循环
j++; //若j<,且j不能整除k,则j加1,再测试去除k
if (j>Math.sqrt(k))
{
System.out.print(k+"\t");
n++;
if (n%10==0) System.out.println( ); //每行输出10个数
}
k=k+2; //测试下一个奇数
}while(k<MAX);
System.out.println("\n共有【"+n+"】个素数");
}
}

//app5_1.java 一维数组
public class app5_1
{
public static void main(String[] args)
{
int i;
int[] a; //声明一个数组a
a=new int[5]; //分配内存空间供整型数组a使用,其元素个数为5
for(i=0;i<5;i++) //对数组元素进行赋值
a[i]=i;
for(i=a.length-1;i>=0;i--) //逆序输出数组的内容
System.out.print("a["+i+"]="+a[i]+ ",\t");
System.out.println("\n数组a的长度是:"+a.length); //输出数组的长度
}
}

//app5_2.java 比较数组元素值的大小
public class app5_2
{
public static void main(String[] args)
{
int i,Max,Sec;
int[] a={8,50,20,7,81,55,76,93}; //声明数组a,并赋初值
if (a[0]>a[1])
{
Max=a[0]; // Max存放最大值
Sec=a[1]; // Sec存放次最大值
}
else
{
Max=a[1];
Sec=a[0];
}
System.out.print("数组的各元素为:"+a[0]+ " "+a[1]);
for(i=2;i<a.length;i++)
{
System.out.print(" " + a[i]); //输出数组a中的各元素
if (a[i]>Max) //判断最大值
{
Sec=Max; //原最大值降为次最大值
Max=a[i]; //a[i]为新的最大值
}
else //即a[i]不是新的最大值,但若a[i]大于次最大值
if (a[i]>Sec) Sec=a[i]; //a[i]为新的次最大值
}
System.out.print("\n其中的最大值是:"+Max); //输出最大值
System.out.println(" 次最大值是:"+Sec); //输出次最大值
}
}

//app5_3.java 约瑟夫环问题
public class app5_3
{
public static void main(String[] args)
{
final int N=13; //总人数N
final int S=3; //从第S个人开始报数
final int M=5; //报数到M的人出圈
int[] p=new int[N];
int i,s,w,j;
s=S;
for(i=1;i<=N;i++) p[i-1]=i; //对每个人进行编号
for(i=N;i>=2;i--) //总人数为N,依次减1
{
s=(s+M-1)%i; //计算下一个开始报数的人的位置
if (s==0) s=i; //最后一个出圈人的位置存入变量s中
w=p[s-1]; //将出圈人的编号保存到变量w中
for (j=s;j<=i-1;j++) p[j-1]=p[j]; //从s位置开始,数组的内容依次前移
p[j-1]=w; //将w存入到空的位置中
}
System.out.println("\n出圈顺序为:");
for (i=p.length-1;i>=0;i--) System.out.print(" "+p[i]);
}
}

//app5_3.java 约瑟夫环问题的另一解法
public class app5_3
{
public static void main(String[] args)
{
final int N=13; //总人数N
final int S=3; //从第S个人开始报数
final int M=5; //报数到M的人出圈
int[] p=new int[N+1];
int[] flag=new int[N+1];
int i,j,n;
for(i=1;i<=N;i++)
{
p[i]=i;
flag[i]=1;
}
i=S; j=1; n=0;
System.out.println("\n出圈顺序为:");
while (true)
{
while (j<M)
{
i=(i+1>N ? 1 : i+1);
j+=flag[i];
}
System.out.print(" "+p[i]);
flag[i]=0;
n++;
if (n==N) break;
j=0;
}
}
}

//app5_4.java 二维数组应用的例子:显示杨辉三角形
public class app5_4
{
public static void main(String[] args)
{
int i,j;
int Level=7;
int[][] iaYong =new int[Level][]; //声明7行二维数组,存放杨辉三角形的各数
System.out.println("杨辉三角形");
for (i=0;i<iaYong.length;i++)
iaYong[i]=new int [i+1]; //定义二维数组的第i行有i+1列
iaYong[0][0]=1;
for (i=1;i<iaYong.length;i++) //计算杨辉三角形
{
iaYong[i][0]=1;
for (j=1;j< iaYong[i].length-1;j++)
iaYong[i][j]= iaYong[i-1][j-1]+ iaYong[i-1][j];
iaYong[i][ iaYong[i].length-1]=1;
}
for(int[] row : iaYong) //利用foreach语句显示出杨辉三角形
{
for(int col : row)
System.out.print(col+ " ");
System.out.println();
}
}
}

// app5_5.java 三维数组应用
public class app5_5
{
public static void main(String[] args)
{
int i,j,k,sum=0;
int[][][] a={{{1,2},{3,4}},{{5,6},{7,8}}}; //声明三维数组并赋初值
for (i=0;i<a.length;i++)
for (j=0;j<a[i].length;j++)
for (k=0;k<a[i][j].length;k++)
{
System.out.println("a["+i+"]["+j+"]["+k+"]="+ a[i][j][k]);
sum+=a[i][j][k]; //计算各元素之和
}
System.out.println("sum="+sum);
}
}

//app5_6.java 字符串应用:判断回文字符串
public class app5_6
{
public static void main(String[] args)
{
String str="rotor";
int i=0,n;
boolean yn=true;
if (args.length>0)
str=args[0];
System.out.println("str="+str);
n=str.length();
char schar,echar;
while (yn && (i<n/2)) //算法1
{
schar=str.charAt(i); //返回字符串str正数第i个位置的字符
echar=str.charAt(n-i-1); //返回字符串str倒数第i个位置的字符
System.out.println("schar="+schar+" echar="+echar);
if (schar==echar)
i++;
else
yn=false;
}
System.out.println("算法1:"+yn);
String temp="",sub1=""; //算法2
for (i=0;i<n;i++)
{
sub1=str.substring(i,i+1); //将str的第i个字符截取下来赋给sub1
temp=sub1+temp; //将截下来的字符放在字符串temp的首位置
}
System.out.println("temp="+temp);
System.out.println("算法2:"+str.equals(temp)); //判断str与temp是否相等
}
}

//app6_1.java 圆柱体类Cylinder
class Cylinder //定义Cylinder类
{
double radius; //定义成员变量radius
int height; //定义成员变量height
double pi=3.14;
void area() //定义无返回值的方法area(),用来计算圆柱底面积
{
System.out.println("底面积="+pi* radius* radius);
}
double volume () //定义返回值为double型的方法volume (),计算体积
{
return (pi* radius* radius)*height;
}
}
public class app6_1 //定义公共类
{
public static void main(String[] args) //程序执行的起始点
{
Cylinder volu;
volu=new Cylinder(); //创建新的对象
volu.radius=2.8; //赋值圆柱volu的底半径
volu.height=5; //赋值圆柱volu的高
System.out.println("底圆半径="+volu.radius); //输出底圆半径
System.out.println("圆柱的高="+volu.height); //输出圆柱的高
System.out.print("圆柱");
volu.area(); //输出面积
System.out.println("圆柱体体积="+volu.volume()); //输出体积
}
}

//app6_2.java 圆柱体类Cylinder的成员在内存中的分配关系
class Cylinder //定义Cylinder类
{
double radius;
int height;
double pi=3.14;
void area()
{
System.out.println("底面积="+pi* radius* radius);
}
double volume()
{
return (pi* radius* radius)*height;
}
}
public class app6_2 //定义公共类
{
public static void main(String[] args)
{
Cylinder volu1,volu2; //声明指向对象的变量volu1和volu2
volu1=new Cylinder(); //创建对象圆柱1:volu1
volu2=new Cylinder(); //创建对象圆柱2:volu2
volu1.radius= volu2.radius=2.5;
volu2.pi=3; //修改volu2的pi值
System.out.println("圆柱1底半径="+volu1.radius);
System.out.println("圆柱2底半径="+volu2.radius);
System.out.println("圆柱1的pi值="+volu1.pi);
System.out.println("圆柱2的pi值="+volu2.pi);
System.out.print("圆柱1");
volu1.area();
System.out.print("圆柱2");
volu2.area();
}
}

//app6_3.java 在类内部调用方法
class Cylinder //定义Cylinder类
{
double radius;
int height;
double pi=3.14;
double area() //定义返回值为double型的方法area (),计算底面积
{
return pi* radius* radius;
}
double volume() //定义返回值为double型的方法volume (),计算体积
{
return area()*height; //在类内调用area()方法
}
}
public class app6_3 //定义公共类
{
public static void main(String[] args)
{
Cylinder volu;
volu=new Cylinder(); //创建新的对象
volu.radius=2.8; //赋值圆柱volu的底半径
volu.height=5; //赋值圆柱volu的高
System.out.println("底圆半径="+volu.radius);
System.out.println("圆柱的高="+volu.height);
System.out.print("圆柱");
System.out.println("底面积="+volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}

//app6_4.java 以一般变量为参数的方法调用
class Cylinder
{
double radius;
int height;
double pi;
void SetCylinder(double r, int h, double p) //具有3个参数的方法
{
pi=p;
radius=r;
height=h;
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app6_4 //定义公共类
{
public static void main(String[] args)
{
Cylinder volu=new Cylinder();
volu.SetCylinder(2.5, 5,3.14); //调用并传递参数到SetCylinder()方法
System.out.println("底圆半径="+volu.radius);
System.out.println("圆柱的高="+volu.height);
System.out.println("圆周率pi="+volu.pi);
System.out.print("圆柱");
System.out.println("底面积="+volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}

//app6_5.java 以数组为参数的方法调用
public class app6_5 //定义主类
{
public static void main(String[] args)
{
int[] a={8,3,7,88,9,23}; //定义一维数组a
LeastNumb MinNumber=new LeastNumb ();
MinNumber.least(a); //将一维数组a传入least()方法
}
}
class LeastNumb //定义另一个类
{
public void least(int[] array) //参数array接收一维整型数组
{
int temp=array[0];
for (int i=1;i<array.length;i++)
if (temp>array[i])
temp=array[i];
System.out.println("最小的数为:"+temp);
}
}

//app6_6.java 返回值是数组类型的方法
public class app6_6
{
public static void main(String[] args)
{
int[][] a={{1,2,3},{4,5,6},{7,8,9}}; //定义二维数组
int[][] b=new int [3][3];
trans pose=new trans(); //创建trans类的对象pose
b=pose.transpose(a); //用数组a调用方法,返回值赋给数组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"); //每输出数组的一行后换行
}
}
}
class trans
{
int temp;
int[][] transpose(int[][] array) //返回值为二维整型数组
{
for (int i=0;i<array.length;i++) //将矩阵转置
for(int j=i+1;j<array[i].length;j++)
{
temp=array[i][j];
array[i][j]=array[j][i];
array[j][i]=temp;
}
return array; //返回二维数组
}
}

//app7_1.java 定义私有成员,使之无法在类外被访问
class Cylinder //定义Cylinder类
{
private double radius; //将数据成员radius声明为私有的
private int height; //将数据成员height声明为私有的
private double pi=3.14; //将数据成员pi声明为私有的,并赋初值
double area()
{
return pi* radius* radius; //在Cylinder类内部,故可访问私有成员
}
double volume()
{
return area()*height; //在类内可以访问私有成员height
}
}
public class app7_1 //定义公共主类
{
public static void main(String[] args)
{
Cylinder volu;
volu=new Cylinder();
volu.radius=2.8;
volu.height=-5;
System.out.println("底圆半径="+volu.radius);
System.out.println("圆柱的高="+volu.height);
System.out.print("圆柱");
System.out.println("底面积="+volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}

//app7_2.java 定义公共方法来访问私有成员
class Cylinder
{
private double radius; //声明私有数据成员
private int height;
private double pi=3.14;
public void SetCylinder(double r, int h) //声明具有2个参数的公共方法
{ //用于对私有数据进行访问
if (r>0&& h>0)
{
radius=r;
height=h;
}
else
System.out.println("您的数据有错误!!");
}
double area()
{
return pi* radius* radius; //在类内可以访问私有成员radius和pi
}
double volume()
{
return area()*height; //在类内可以访问私有成员height
}
}
public class app7_2 //定义公共主类
{
public static void main(String[] args)
{
Cylinder volu=new Cylinder();
volu.SetCylinder(2.5, -5); //通过公共方法SetCylinder()访问私有数据
System.out.println("圆柱底面积="+volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}

//app7_3.java 方法的重载
class Cylinder
{
private double radius;
private int height;
private double pi=3.14;
private String color;
public double SetCylinder(double r, int h) //重载方法
{
radius=r;
height=h;
return r+h;
}
public void SetCylinder(String str) //重载方法
{
color=str;
}
public void show()
{
System.out.println("圆柱的颜色为:"+color);
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_3 //定义主类
{
public static void main(String[] args)
{
double r_h;
Cylinder volu=new Cylinder();
r_h=volu.SetCylinder(2.5, 5); //设置圆柱的底半径和高
volu.SetCylinder("红色"); //设置圆柱的颜色
System.out.println("圆柱底和高之和="+r_h);
System.out.println("圆柱体体积="+volu.volume());
volu.show();
}
}

//app7_4.java 构造方法的使用
class Cylinder //定义类Cylinder
{
private double radius;
private int height;
private double pi=3.14;
public Cylinder(double r, int h) //定义构造方法
{
radius=r;
height=h;
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_4 //定义主类
{
public static void main(String[] args)
{
Cylinder volu=new Cylinder(3.5, 8); //创建对象并调用构造方法
System.out.println("圆柱底积="+ volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}

//app7_5.java 构造方法的重载
class Cylinder //定义类Cylinder
{
private double radius;
private int height;
private double pi=3.14;
String color;
public Cylinder() //定义无参数的构造方法
{
radius=1;
height=2;
color="绿色";
}
public Cylinder(double r, int h, String str) //定义有三个参数的构造方法
{
radius=r;
height=h;
color=str;
}
public void SetColor()
{
System.out.println("该圆柱的颜色为:"+color);
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_5 //定义主类
{
public static void main(String[] args)
{
Cylinder volu1=new Cylinder();
System.out.println("圆柱1底面积="+ volu1.area());
System.out.println("圆柱1体积="+volu1.volume());
volu1.SetColor();
Cylinder volu2=new Cylinder(2.5, 8, "红色");
System.out.println("圆柱2底面积="+ volu2.area());
System.out.println("圆柱2体积="+volu2.volume());
volu2.SetColor();
}
}

//app7_6.java 从某一构造方法调用另一构造方法
class Cylinder //定义类Cylinder
{
private double radius;
private int height;
private double pi=3.14;
String color;
public Cylinder() //定义无参数的构造方法
{
this(2.5, 5, "红色"); //用this关键字来调用另一构造方法
System.out.println("无参构造方法被调用了");
}
public Cylinder(double r, int h, String str) //定义有三个参数的构造方法
{
System.out.println("有参构造方法被调用了");
radius=r;
height=h;
color=str;
}
public void show()
{
System.out.println("圆柱底半径为:"+ radius);
System.out.println("圆柱体的高为:"+ height);
System.out.println("圆柱的颜色为:"+color);
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_6 //主类
{
public static void main(String[] args)
{
Cylinder volu=new Cylinder();
System.out.println("圆柱底面积="+ volu.area());
System.out.println("圆柱体体积="+volu.volume());
volu.show();
}
}

//app7_7.java 公共构造方法与私有构造方法
class Cylinder //定义类Cylinder
{
private double radius;
private int height;
private double pi=3.14;
String color;
private Cylinder() //定义私有的构造方法
{
System.out.println("无参构造方法被调用了");
}
public Cylinder(double r, int h, String str) //定义有三个参数的构造方法
{
this(); //在公共构造方法中用this关键字来调用另一构造方法
radius=r;
height=h;
color=str;
}
public void show()
{
System.out.println("圆柱底半径为:"+ radius);
System.out.println("圆柱体的高为:"+ height);
System.out.println("圆柱的颜色为:"+color);
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_7 //主类
{
public static void main(String[] args)
{
Cylinder volu=new Cylinder(2.5,5,"蓝色");
System.out.println("圆柱底面积="+ volu.area());
System.out.println("圆柱体体积="+volu.volume());
volu.show();
}
}

//app7_8.java 静态变量的使用
class Cylinder //定义类Cylinder
{
private static int num=0; //声明num为静态变量
private static double pi=3.14; //声明pi为静态变量,并赋初值
private double radius;
private int height;
public Cylinder(double r, int h) //定义有2个参数的构造方法
{
radius=r;
height=h;
num++; //当构造方法Cylinder()被调用时,num便加1
}
public void count() // count()方法用来显示目前创建对象的个数
{
System.out.print("创建了"+num+"个对象:");
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_8 //主类
{
public static void main(String[] args)
{
Cylinder volu1=new Cylinder(2.5,5);
volu1.count();
System.out.println("圆柱1的体积="+volu1.volume());
Cylinder volu2=new Cylinder(1.0,2);
volu2.count();
System.out.println("圆柱2的体积="+volu2.volume());
}
}

//app7_9.java 静态方法的使用
class Cylinder //定义类Cylinder
{
private static int num=0;
private static double pi=3.14;
private double radius;
private int height;
public Cylinder(double r, int h)
{
radius=r;
height=h;
num++; //当构造方法Cylinder()被调用时,num便加1
}
public static void count() // 声明count()为静态方法
{
System.out.println("创建了"+num+"个对象");
}
double area()
{
return pi* radius* radius;
}
double volume()
{
return area()*height;
}
}
public class app7_9 //主类
{
public static void main(String[] args)
{
Cylinder.count(); //在对象产生之前用Cylinder类名调用count()方法
Cylinder volu1=new Cylinder(2.5,3);
volu1.count(); //用对象volu1调用count()方法
System.out.println("圆柱1的体积="+volu1.volume());
Cylinder volu2=new Cylinder(1.0,2);
Cylinder.count(); //用类名Cylinder直接调用count()方法
System.out.println("圆柱2的体积="+volu2.volume());
}
}

//app7_10.java 对象的赋值
class Cylinder //定义类Cylinder
{
private static double pi=3.14;
private double radius;
private int height;
public Cylinder(double r, int h)
{
radius=r;
height=h;
}
public void SetCylinder(double r, int h)
{
radius=r;
height=h;
}
double volume()
{
return pi* radius* radius *height;
}
}
public class app7_10 //主类
{
public static void main(String[] args)
{
Cylinder volu1,volu2; //声明volu1,volu2两个引用型变量
volu1=new Cylinder(2.5,5); //创建对象,并将volu1指向它
System.out.println("圆柱1的体积="+volu1.volume());
volu2= volu1; //将volu1赋值给volu2,volu2也指向了该对象
volu2.SetCylinder(1.0, 2); //重新设置圆柱的底半径和高
System.out.println("圆柱2的体积="+volu1.volume());
}
}

//app7_11.java 向方法内传递对象
class Cylinder //定义类Cylinder
{
private static double pi=3.14;
private double radius;
private int height;
public Cylinder(double r, int h)
{
radius=r;
height=h;
}
public void compare(Cylinder volu)
{
if (this==volu) //判断this与volu是否指向同一对象
System.out.println("这两个对象相等");
else
System.out.println("这两个对象不相等");
}
}
public class app7_11 //主类
{
public static void main(String[] args)
{
Cylinder volu1=new Cylinder(1.0,2);
Cylinder volu2=new Cylinder(1.0,2);
Cylinder volu3= volu1;
volu1.compare(volu2); //调用compare(),比较volu1与volu2是否相等
volu1.compare(volu3); //调用compare(),比较volu1与volu3是否相等
}
}

//app7_12.java 方法的返回值为对象
class Person //定义类Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name=name;
this.age=age;
}
public Person compare(Person P) //返回值的类型为对象
{
if (this.age>P.age)
return this; //返回调用该方法的对象
else
return P; //返回参数对象
}
}
public class app7_12 //主类
{
public static void main(String[] args)
{
Person Per1=new Person ("张三",20);
Person Per2=new Person ("李四",21);
Person Per3;
Per3= Per1.compare(Per2);
if (Per3==Per1)
System.out.println("张三年龄大");
else
System.out.println("李四年龄大");
}
}

//app7_13.java 对象数组的应用
class Person //定义类Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name=name;
this.age=age;
}
public void show()
{
System.out.println("姓名:"+name+" 年龄:"+age);
}
}
public class app7_13 //主类
{
public static void main(String[] args)
{
Person[] Per; //声明类类型的数组
Per=new Person[3]; //用new为数组分配内存空间
Per[0]=new Person("张三",20);
Per[1]=new Person("李四",21);
Per[2]=new Person("王二",19);
Per[2].show(); //利用对象Per[2]调用show()方法
Per[0].show(); //利用对象Per[0]调用show()方法
}
}

//app7_14.java 以对象数组为参数进行方法调用
class Person //定义类Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name=name;
this.age=age;
}
public static int min_age(Person[] p) //以对象数组作为参数传递给方法
{
int min=Integer.MAX_VALUE;
for (int i=0;i<p.length;i++)
if (p[i].age<min)
min=p[i].age;
return min;
}
}
public class app7_14
{
public static void main(String[] args)
{
Person[] Per=new Person[3];
Per[0]=new Person("张三",20);
Per[1]=new Person("李四",21);
Per[2]=new Person("王二",19);
System.out.println("最小的年龄为:"+ Person. min_age(Per));
}
}

//app8_1.java 继承的简单例子
class Person //Person类是java.lang.Object类的子类
{
private String name; //name表示姓名
private int age; //age表示年龄
public Person() //定义无参构造方法
{
System.out.println("调用了个人构造方法Person()");
}
public void SetNameAge(String name, int age)
{
this.name=name;
this.age=age;
}
public void show()
{
System.out.println("姓名:"+name+" 年龄:"+age);
}
}
class Student extends Person //定义Student类,继承自Person类
{
private String department;
public Student() // Student类的构造方法
{
System.out.println("调用了学生构造方法Student()");
}
public void SetDepartment(String dep)
{
department=dep;
System.out.println("我是"+department +"的学生");
}
}
public class app8_1 //主类
{
public static void main(String[] args)
{
Student stu=new Student(); //创建Student对象
stu.SetNameAge("张小三",21); //调用父类的SetNameAge()方法
stu.show(); //调用父类的show()方法
stu.SetDepartment("计算机系"); //调用子类的SetDepartment{}方法
}
}

//app8_2.java 调用父类中的特定构造方法
class Person //定义Person类
{
private String name;
private int age;
public Person() //定义无参构造方法
{
System.out.println("调用了Person的无参构造方法");
}
public Person(String name, int age) //定义有参构造方法
{
System.out.println("调用了Person的有参构造方法");
this.name=name;
this.age=age;
}
public void show()
{
System.out.println("姓名:"+name+" 年龄:"+age);
}
}
class Student extends Person //定义继承自Person类的子类Student
{
private String department;
public Student() // Student的无参构造方法
{
System.out.println("调用了学生的无参构造方法Student()");
}
public Student (String name,int age,String dep) //定义Student的有参构造方法
{
super(name,age); //调用父类的有参构造方法,在第10行定义的
department=dep;
System.out.println("我是"+department +"的学生");
System.out.println("调用了学生的有参构造方法Student(String dep) ");
}
}
public class app8_2 //主类
{
public static void main(String[] args)
{
Student stu1=new Student(); //创建对象,并调用无参构造方法
Student stu2=new Student("李小四",23, "信息系"); //创建对象,并调用有参构造方法
stu1.show();
stu2.show();
}
}

//app8_3.java 用protected修饰符和super关键字访问父类的成员
class Person //定义Person类
{
protected String name;
protected int age;
public Person() {} //定义“不做事”的无参构造方法
public Person(String name, int age) //定义有参构造方法
{
this.name=name;
this.age=age;
}
protected void show()
{
System.out.println("姓名:"+name+" 年龄:"+age);
}
}
class Student extends Person //定义子类Student,其父类为Person
{
private String department;
int age=20; //新添加了一个与父类的成员变量age同名的成员变量
public Student (String xm,String dep) //定义Student类的有参构造方法
{
name=xm; //在子类里直接访问父类的protected成员name
department=dep;
super.age=25; //利用super关键字将父类的成员变量age赋值为25
System.out.println("子类Student中的成员变量age="+age);
super.show(); //去掉super而只写show()亦可
System.out.println("系别:"+ department );
}
}
public class app8_3 //主类
{
public static void main(String[] args)
{
Student stu=new Student("李小四","信息系");
}
}

//app8_4.java 方法的覆盖
class Person //定义Person类
{
protected String name;
protected int age;
public Person(String name, int age) //定义构造方法
{
this.name=name;
this.age=age;
}
protected void show()
{
System.out.println("姓名:"+name+" 年龄:"+age);
}
}
class Student extends Person //定义子类Student,其父类为Person
{
private String department;
public Student (String name,int age,String dep) //定义构造方法
{
super(name,age);
department=dep;
}
protected void show() //覆盖父类Person中的同名方法
{
System.out.println("系别:"+ department);
}
}
public class app8_4
{
public static void main(String[] args)
{
Student stu=new Student("王永涛",24, "电子");
stu.show();
}
}

//app8_5.java 通过父类的对象来调用子类的成员
class Person //定义Person类
{
protected String name;
protected int age;
public Person(String name, int age) //定义构造方法
{
this.name=name;
this.age=age;
}
protected void show()
{
System.out.println("姓名:"+name+" 年龄:"+age);
}
}
class Student extends Person //定义子类Student,其父类为Person
{
private String department;
public Student (String name,int age,String dep) //定义构造方法
{
super(name,age);
department=dep;
}
protected void show()
{
System.out.println("系别:"+ department);
}
public void subshow()
{
System.out.println("我在子类中");
}
}
public class app8_5 //主类
{
public static void main(String[] args)
{
Person per=new Student("王永涛",24, "电子"); //声明父类变量per指向对象
per.show(); //利用父类对象per调用show()方法
//per.subshow();
}
}

//app8_6.java 父类中的final方法不允许覆盖
class AAA
{
static final double pi=3.14; //声明静态常量
public final void show() //声明最终方法
{
System.out.println("pi="+pi);
}
}
class BBB extends AAA
{
private int num=100;
public void show() //错误,不可覆盖父类的方法
{
System.out.println("num="+num);
}
}
public class app8_6
{
public static void main(String[] args)
{
BBB ex=new BBB();
ex.show();
}
}

//app8_7.java 对象的两种比较方式
class A{
int a=1;
}
public class app8_7{
public static void main(String[] args){
A obj1=new A();
A obj2=new A();
String s1,s2,s3="abc",s4="abc";
s1=new String ("abc");
s2=new String ("abc");
System.out.println("s1.equals(s2)是"+(s1.equals(s2)));
System.out.println("s1==s3是"+(s1==s3));
System.out.println("s1.equals(s3)是"+(s1.equals(s3)));
System.out.println("s3==s4是"+(s3==s4));
System.out.println("s2.equals(s3)是"+(s2.equals(s3)));
System.out.println("s1==s2是"+(s1==s2));
System.out.println("obj1==obj2是"+(obj1==obj2));
System.out.println("obj1.equals(obj2)是"+(obj1.equals(obj2)));
obj1=obj2;
System.out.println("obj1=obj2后obj1==obj2是"+(obj1==obj2));
System.out.println("obj1=obj2后obj1.equals(obj2)是"+(obj1.equals(obj2)));
}
}

//app8_8.java 利用getClass()方法返回调用该方法所属的类
class Person
{
protected String name;
public Person(String xm) //定义构造方法
{
name=xm;
}
}
public class app8_8 //主类
{
public static void main(String[] args)
{
Person per=new Person("张三");
Class obj=per.getClass(); //用变量per调用getClass()方法
System.out.println("对象per所属的类为:"+obj);
}
}

// Person .java
public class Person //定义Person类
{
static int count=0; //定义静态变量count
protected String name;
protected int age;
public Person(String n1,int a1) //构造方法
{
name=n1;
age=a1;
this.count++; //调用父类的静态变量
}
public String toString()
{
return this.name+" , "+this.age;
}
public void display()
{
System.out.print("本类名="+this.getClass().getName()+";");
System.out.println("父类名="+this.getClass().getSuperclass().getName());
System.out.print("Person.count="+this.count+ " ");
System.out.print("Student.count="+Student.count+ " ");
Object obj=this;
if(obj instanceof Student) //判断对象属于哪个类
System.out.println(obj.toString()+"是Student类对象。");
else if(obj instanceof Person)
System.out.println(obj.toString()+"是Person类对象。");
}
}
class Student extends Person //子类Student继承自父类Person
{
static int count=0; //隐藏了父类的count
protected String dept;
protected Student(String n1,int a1,String d1)
{
super(n1,a1); //调用父类的构造方法
dept=d1;
this.count++; //调用子类的静态变量
}
public String toString() //覆盖父类的同名方法
{
return super.toString()+","+dept; //调用父类的同名方法
}
public void display()
{
super.display(); //调用父类的方法
System.out.print("super.count="+super.count); //引用父类的变量
System.out.println(" ;this.count="+this.count);
}
public static void main(String[] args)
{
Person per=new Person("王永涛",23);
per.display();
Student stu=new Student("张小三",22,"计算机系");
stu.display();
}
}

//app8_10.java 抽象类的说明
abstract class Shape //定义形状抽象类Shape
{
protected String name;
public Shape(String xm) //抽象类中的一般的方法,本方法是构造方法
{
name=xm;
System.out.print("名称:"+name);
}
abstract public double getArea(); //声明抽象方法
abstract public double getLength(); //声明抽象方法
}
class Circle extends Shape //定义继承自Shape的圆形子类Circle
{
private double pi=3.14;
private double radius;
public Circle(String shapename,double r) //构造方法
{
super(shapename);
radius=r;
}
public double getArea() //实现抽象类中的getArea()方法
{
return pi*radius*radius;
}
public double getLength() //实现抽象类中的getLength()方法
{
return 2*pi*radius;
}
}
class Rectangle extends Shape //定义继承自Shape的矩形子类Rectangle
{
private double width;
private double height;
public Rectangle(String shapename,double width,double height) //构造方法
{
super(shapename);
this.width=width;
this.height=height;
}
public double getArea() //实现抽象类中的getArea()方法
{
return width*height;
}
public double getLength() //实现抽象类中的getLength()方法
{
return 2*(width+height);
}
}
public class app8_10 //定义主类
{
public static void main(String[] args)
{
Shape rect =new Rectangle("长方形",6.5,10.3); //声明父类对象,指向子类对象
System.out.print(";面积="+rect.getArea());
System.out.println(";周长="+rect.getLength());
Shape circle=new Circle("圆",10.2); //声明父类对象circle,指向子类对象
System.out.print(";面积="+circle.getArea());
System.out.println(";周长="+circle.getLength());
}
}

//app8_11.java 接口的实现
interface IShape //定义接口
{
final double pi=3.14;
abstract double getArea(); //声明抽象方法
abstract double getLength(); //声明抽象方法
}
class Circle implements IShape //以IShape接口来实现Circle类
{
double radius;
public Circle(double r)
{
radius=r;
}
public double getArea() //实现接口中的getArea()方法
{
return pi*radius*radius;
}
public double getLength() //实现接口中的getLength()方法
{
return 2*pi*radius;
}
}
class Rectangle implements IShape //以IShape接口来实现Rectangle类
{
private double width;
private double height;
public Rectangle(double width,double height)
{
this.width=width;
this.height=height;
}
public double getArea() //实现接口中的getArea()方法
{
return width*height;
}
public double getLength() //实现接口中的getLength()方法
{
return 2*(width+height);
}
}
public class app8_11 //主类
{
public static void main(String[] args)
{
IShape circle=new Circle(5.0); //声明父接口变量circle,指向子类对象
System.out.print("圆面积="+circle.getArea());
System.out.println(";周长="+circle.getLength());
Rectangle rect =new Rectangle(6.5,10.8); //声明Rectangle类的变量rect
System.out.print("矩形面积="+rect.getArea());
System.out.println(";周长="+rect.getLength());
}
}

// Cylinder.java
interface Face1 //定义接口Face1
{
double pi=3.14;
abstract double area();
}
interface Face2 //定义接口Face2
{
abstract void setColor(String c);
}
interface Face3 extends Face1,Face2 //接口的多重继承
{
abstract void volume();
}
public class Cylinder implements Face3 //以Face3接口实现Cylinder类
{
private double radius;
private int height;
protected String color;
public Cylinder(double r, int h)
{
radius=r;
height=h;
}
public double area() //实现Face1接口中的方法
{
return pi*radius*radius;
}
public void setColor(String c) //实现Face2接口中的方法
{
color=c;
System.out.println("颜色:"+color);
}
public void volume() //实现Face3接口中的方法
{
System.out.println("圆柱体体积="+ area()*height);
}
public static void main(String[] args)
{
Cylinder volu=new Cylinder(3.0,2);
volu.setColor("红色");
volu.volume();
}
}

//Cylinder.java 多重继承
interface Face1 //定义接口Face1
{
double pi=3.14;
abstract double area();
}
interface Face2 //定义接口Face2
{
abstract void volume();
}
public class Cylinder implements Face1,Face2 //多重继承
{
private double radius;
private int height;
public Cylinder(double r, int h)
{
radius=r;
height=h;
}
public double area()
{
return pi*radius*radius;
}
public void volume()
{
System.out.println("圆柱体体积="+area()*height);
}
public static void main(String[] args)
{
Cylinder volu=new Cylinder(5.0,2);
volu.volume();
}
}

//Group.java 内部类与外部类的访问规则
public class Group
{
private int age; //声明外部类的私有成员变量
public class Student //声明内部类
{
String name; //声明内部类的成员变量
public Student(String n,int a) //定义内部类的构造方法
{
name=n; //访问内部类的成员变量name
age=a; //访问外部类的成员变量age
}
public void output() //内部类的成员方法
{
System.out.println("姓名:"+this.name+";年龄:"+age);
}
}
public void output() //定义外部类的成员方法
{
Student stu=new Student("刘 洋",24); //创建内部类对象stu
stu.output(); //通过stu调用内部类的成员方法
}
public static void main(String[] args)
{
Group G=new Group();
G.output(); //用G调用外部类的方法
}
}

//app8_15.java 匿名内部类
public class app8_15
{
public static void main(String[] args)
{
(
new Inner() //创建匿名内部类Inner的对象
{
void setName(String n)
{
name=n;
System.out.println("姓名:"+name);
}
}
).setName("张 华"); //执行匿名内部类里所定义的方法
}
static class Inner //定义内部类
{
String name;
}
}

//app9_1.java 异常的产生
public class app9_1
{
public static void main(String[] args)
{
int i;
int[] a={1,2,3,4}; //定义并初始化数组
for (i=0;i<5;i++)
System.out.println(" a["+i+"]="+a[i]);
System.out.println("5/0"+(5/0));
}
}

//app9_2.java 异常的捕获与处理
public class app9_2
{
public static void main(String[] args)
{
int i;
int[] a={1,2,3,4};
for (i=0;i<5;i++)
{
try
{
System.out.print("a["+i+"]/"+i+"="+(a[i]/i));
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.print("捕获到了数组下标越界异常");
}
catch(ArithmeticException e)
{
System.out.print("异常类名称是:"+e); //显示异常信息
}
catch(Exception e)
{
System.out.println("捕获"+e.getMessage()+"异常!"); //显示异常信息
}
finally
{
System.out.println(" finally i="+i);
}
}
System.out.println("继续!!");
}
}

//app9_3.java 使用throw语句在方法之中抛出异常
public class app9_3
{
public static void main(String[] args)
{
int a=5,b=0;
try
{
if (b==0)
throw new ArithmeticException(); //抛出异常
else
System.out.println(a+"/"+b+"="+a/b); //若不抛出异常,则运行此行
}
catch(ArithmeticException e)
{
System.out.println("异常:"+e+" 被抛出了!");
}
}
}

//app9_4.java 使用throw语句在方法之中抛出异常
public class app9_4
{
public void run(byte k)
{
byte y=1,i;
System.out.print(k+"!=");
for (i=1;i<=k;i++)
{
try
{
if (y>Byte.MAX_VALUE/i) //Byte类的常量,表示最大值
throw new Exception("溢出!!"); //溢出时抛出异常
else
y=(byte)(y*i);
}
catch (Exception e)
{
System.out.println("异常:"+e.getMessage());
e.printStackTrace(); //显示异常信息
System.exit(0); //程序正常结束
}
}
System.out.println(y);
}
public static void main(String[] args)
{
app9_4 a=new app9_4();
for(byte i=1;i<10;i++)
a.run(i);
}
}

//app9_5.java 使用throws语句在方法之中抛出异常
public class app9_5
{
static void check(String str1) throws NumberFormatException
{
char ch;
for (int i=0;i<str1.length();i++)
{
ch=str1.charAt(i);
if (!Character.isDigit(ch)) //判断参数中字符是否为数字
throw new NumberFormatException(); //方法中抛出异常
}
}
public static void main(String[] args) throws Exception //抛出异常给系统处理
{
int num;
try
{
check(args[0]);
num=Integer.parseInt(args[0]);
if (num>60)
System.out.println("成绩为:"+num+" 及格");
else
System.out.println("成绩为:"+num+" 不及格");
}
catch (NumberFormatException ex) //check()方法所引发的异常
{
System.out.println("输入的参数不是数值类型");
}
catch (Exception e)
{
System.out.println("命令行中没有提供参数");
}
}
}

//app9_6.java 利用IOException的异常处理
import java.io.*; //加载java.io类库里的所有类
public class app9_6
{
public static void main(String[] args)
{
String str;
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
while (true)
{
try
{
System.out.print("请输入字符串:");
str=buf.readLine(); //将从键盘输入的数据赋给变量str
if (str.length()>0)
break;
else
throw new IOException(); //抛出输入/输出异常
}
catch (IOException e)
{
System.out.println("必须输入字符串!!");
continue;
}
}
String s=str.toUpperCase(); //将str中的内容转换成大写,赋给变量s
System.out.println("转换后的字符串为:"+s);
}
}

//app9_7.java 自定义异常类的用法
import java.io.*;
class DevideByMinusException extends Exception //自定义异常类
{
int devisor;
public DevideByMinusException() //无参构造方法
{
System.out.println("除数不允许为负数");
}
public DevideByMinusException(String msg,int devisor) //有参构造方法
{
super(msg);
this.devisor=devisor;
}
public int getDevisor()
{
return devisor;
}
}
class Test
{
public double devide(int x,int y) throws ArithmeticException, DevideByMinusException
{
if (y<0)
throw new DevideByMinusException("除数为负",y);
double result=x/y;
return result;
}
}
public class app9_7
{
public static void main(String[] args)
{
int a,b;
String str1,str2;
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.print("请输入被除数x=");
str1=buf.readLine(); //将输入的文字赋值给字符串变量str1
a=Integer.parseInt(str1); //将str1转成int类型后赋给a
System.out.print("请输入除数y=");
str2=buf.readLine(); //将输入的文字赋值给字符串变量str2
b=Integer.parseInt(str2); //将str2转成int类型后赋给b
double result=new Test().devide(a,b);
System.out.println(a+"/"+b+"="+ result);
}
catch (DevideByMinusException e)
{
System.out.println("异常名:"+e);
System.out.println(e.getMessage());
System.out.println("除数是:"+e.getDevisor());
}
catch (ArithmeticException e)
{
System.out.println("异常名:"+e);
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println("程序抛出了未知异常");
System.out.println(e.getMessage());
}
System.out.println("程序执行完毕!");
}
}

//app10_1.java 利用输入输出流读写文件
import java.io.*;
class app10_1
{
public static void main(String[] args)
{
FileInputStream fin; //声明文件输入流对象fin
FileOutputStream fout; //声明文件输出流对象fout
char ch;
int data;
try
{
fin =new FileInputStream(FileDescriptor.in); //创建文件输入流对象fin
fout =new FileOutputStream("d:\\cgj\\myfile"); //创建文件输出流对象fout
System.out.println("请输入一串字符,并以 # 结束:");
while ((ch=(char)fin.read())!='#')
fout.write(ch);
fin.close();
fout.close();
System.out.println();
fin=new FileInputStream("d:\\cgj\\myfile");
fout=new FileOutputStream(FileDescriptor.out);
while (fin.available()>0)
{
data=fin.read();
fout.write(data);
}
fin.close();
fout.close();
}
catch (FileNotFoundException e)
{
System.out.println("文件没找到!");
}
catch (IOException e)
{ }
}
}

//app10_2.java 读写二进制文件
import java.io.*;
public class app10_2
{
public static void main(String[] args) throws IOException
{
FileInputStream fi=new FileInputStream("d:\\cgj\\风景.jpg");
FileOutputStream fo=new FileOutputStream("d:\\cgj\\风景1.jpg");
System.out.println("文件的大小="+fi.available()); //输出文件的大小
byte[] b=new byte[fi.available()]; //创建byte类型的数组b
fi.read(b); //将图形文件读入b数组
fo.write(b); //将b数组里的数据写入新文件my_icon.gif
System.out.println("文件已被拷贝并被更名");
fi.close();
fo.close();
}
}

//app10_3.java 顺序输入流的应用
import java.io.*;
import java.util.*;
public class app10_3
{
public static void main(String[] args)
{
FilesList mylist=new FilesList(args);
SequenceInputStream sin;
int data;
try
{
sin=new SequenceInputStream(mylist);
while ((data=sin.read())!=-1)
System.out.print((char)data);
sin.close();
}
catch (FileNotFoundException e)
{
System.out.println("文件不存在!");
}
catch (IOException e)
{ }
}
}
class FilesList implements Enumeration //FilesList类实现Enumeration接口
{
String[] MyFilesList;
int current=0;
public FilesList(String[] fileslist)
{
MyFilesList=fileslist;
}
public boolean hasMoreElements()
{
if (current<MyFilesList.length)
return true;
else
return false;
}
public Object nextElement()
{
FileInputStream in=null;
if (!hasMoreElements())
throw new NoSuchElementException("没有更多的文件!!");
else
{
String nextElement=MyFilesList[current];
current++;
try
{
in=new FileInputStream(nextElement);
}
catch (FileNotFoundException e)
{
System.err.println(nextElement +"文件不能打开");
}
}
return in;
}
}

//app10_4.java 数据流的应用
import java.io.*;
public class app10_4
{
public static void main(String[] args)
{
FileOutputStream fout;
DataOutputStream dout;
FileInputStream fin;
DataInputStream din;
try
{
fout=new FileOutputStream("d:\\temp");
dout=new DataOutputStream(fout);
dout.writeInt(10);
dout.writeLong(12345);
dout.writeFloat(3.1415926f);
dout.writeDouble(987654321.123);
dout.writeBoolean(true);
dout.writeChars("Goodbye! ");
dout.close();
}
catch (IOException e) { }
try
{
fin=new FileInputStream("d:\\temp");
din=new DataInputStream(fin);
System.out.println(din.readInt());
System.out.println(din.readLong());
System.out.println(din.readFloat());
System.out.println(din.readDouble());
System.out.println(din.readBoolean());
char ch;
while ((ch=din.readChar())!='\0')
System.out.print(ch);
din.close();
}
catch (FileNotFoundException e)
{
System.out.println("文件未找到!!");
}
catch (IOException e) { }
}
}

//app10_5.java 数据流的应用
import java.io.*;
public class app10_5
{
public static void main(String[] args)
{
try
{
byte[] b=new byte[128]; //设置输入缓冲区
System.out.print("请输入字符:");
int count=System.in.read(b); //读取标准输入流,将回车符和换行符也存放到b数组中
System.out.println("输入的是:");
for (int i=0;i<count;i++)
System.out.print(b[i]+ " "); //输出b中元素的ASCII值
System.out.println();
for (int i=0;i<count-2;i++) //不显示回车符与换行符
System.out.print((char)b[i]+ " "); //按字符方式输出b的元素
System.out.println();
System.out.println("输入的字符个数为"+count);
Class InClass=System.in.getClass();
Class OutClass=System.out.getClass();
System.out.println("in所在的类是:"+InClass.toString());
System.out.println("out所在的类是:"+OutClass.toString());
}
catch (IOException e) { }
}
}

//app10_6.java FileReader类的使用
import java.io.*;
public class app10_6
{
public static void main(String[] args) throws IOException
{
char[] c=new char[500]; //创建可容纳500个字符的数组
FileReader fr=new FileReader("d:\\java\\test.txt"); //创建对象fr
int num=fr.read(c); //将数据读入字符数组c内,并返回读取的字符数
String str=new String(c,0,num); //将字符串数组转换成字符串
System.out.println("读取的字符个数为:"+num+",其内容如下:");
System.out.println(str);
}
}

//app10_7.java FileReader类的使用
import java.io.*;
public class app10_7
{
public static void main(String[] args) throws IOException
{
FileWriter fw=new FileWriter("d:\\java\\test.txt");
char[] c={'H', 'e', 'l', 'l', 'o', '\r', '\n'};
String str="欢迎使用Java!";
fw.write(c); //将字符数组写到文件里
fw.write(str); //将字符串写到文件里
fw.close();
}
}

//app10_8.java BufferedReader类的使用
import java.io.*;
public class app10_8
{
public static void main(String[] args) throws IOException
{
String thisLine;
int count=0;
try
{
FileReader fr=new FileReader("d:\\java\\test.txt");
BufferedReader bfr=new BufferedReader(fr);
while ((thisLine=bfr.readLine())!=null) //每次读取一行,直到文件结束
{
count++; //计算读取的行数
System.out.println(thisLine);
}
System.out.println("共读取了"+count+"行");
bfr.close(); //关闭文件
}
catch (IOException ioe)
{
System.out.println("错误! "+ioe);
}
}
}

//app10_9.java
import java.io.*;
public class app10_9
{
public static void main(String[] args) throws IOException
{
String str=new String();
try
{
BufferedReader in=new BufferedReader(new FileReader("d:\\java\\test.txt"));
BufferedWriter out=new BufferedWriter(new FileWriter("d:\\java\\test1.txt"));
while ((str=in.readLine())!=null)
{
System.out.println(str); //在显示器上输出
out.write(str); //将读取到的一行数据写入到输出流中
out.newLine(); //写入回车换行符
}
out.flush(); //将缓冲区中的数据全部写入到文件中
in.close();
out.close();
}
catch (IOException ioe)
{
System.out.println("错误! "+ioe);
}
}
}

//app10_10.java
import java.io.*;
public class app10_10
{
public static void main(String[] args) throws IOException
{
String str=new String();
try
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(isr);
String sdir="d:\\cgj";
String sfile;
File Fdir1=new File(sdir);
if (Fdir1.exists() && Fdir1.isDirectory())
{
System.out.println("文件夹:"+sdir+"已经存在");
for (int i=0;i<Fdir1.list().length;i++)
System.out.println((Fdir1.list())[i]);
File Fdir2=new File("d:\\cgj\\temp");
if (!Fdir2.exists())
Fdir2.mkdir();
System.out.println();
System.out.println("建立新文件夹后的文件列表");
for (int i=0;i<Fdir1.list().length;i++)
System.out.println((Fdir1.list())[i]);
}
System.out.print("请输入该文件夹中的一个文件名:");
sfile=in.readLine(); //从键盘上读取数据
File Ffile=new File(Fdir1,sfile);
if (Ffile.isFile())
{
System.out.print("文件名:"+Ffile.getName());
System.out.print(";所在文件夹:"+Ffile.getPath());
System.out.println(";文件大小:"+Ffile.length()+"字节");
}
}
catch (IOException e)
{
System.out.println(e.toString());
}
}
}

//app10_11.java RandomAccessFile类的应用
import java.io.*;
public class app10_11
{
public static void main(String[] args) throws IOException
{
StringBuffer stfDir=new StringBuffer();
System.out.println("请输入文件所在的路径");
char ch;
while ((ch=(char)System.in.read())!='\n')
stfDir.append(ch);
File dir=new File(stfDir.toString());
System.out.println("请输入欲读取的文件名");
StringBuffer stfFilename=new StringBuffer();
char c;
while ((c=(char)System.in.read())!='\n')
stfFilename.append(c);
File readFrom=new File(dir,stfFilename.toString());
if (readFrom.isFile() && readFrom.canWrite() && readFrom.canRead())
{
RandomAccessFile rafFile=new RandomAccessFile(readFrom,"rw");
while (rafFile.getFilePointer()<rafFile.length())
System.out.println(rafFile.readLine());
rafFile.close();
}
else
System.out.println("文件不可读!");
}
}

//app11_1.java 创建Thread类的子类来创建线程
class myThread extends Thread //创建Thread类的子类myThread
{
private String who;
public myThread(String str) //构造方法,用于设置成员变量who
{
who=str;
}
public void run() //覆盖Thread类里的run()方法
{
for (int i=0;i<5;i++)
{
try
{
sleep ((int)(1000*Math.random())); // sleep()方法必须写在try-catch块内
}
catch (InterruptedException e) {}
System.out.println(who+"正在运行!!");
}
}
}
public class app11_1
{
public static void main(String[] args)
{
myThread you=new myThread("你");
myThread she=new myThread("她");
you.start(); //注意调用的是start()方法而不是run()方法
she.start(); //注意调用的是start()方法而不是run()方法
System.out.println("主方法main()运行结束!");
}
}

//app11_2.java 利用Runnable接口来创建线程
class myThread implements Runnable //由Runnable接口实现myThread类
{
private String who;
public myThread(String str) //构造方法,用于设置成员变量who
{
who=str;
}
public void run() //实现run()方法
{
for (int i=0;i<5;i++)
{
try
{
Thread.sleep ((int)(1000*Math.random()));
}
catch (InterruptedException e)
{
System.out.println(e.toString());
}
System.out.println(who+"正在运行!!");
}
}
}
public class app11_2
{
public static void main(String[] args)
{
myThread you=new myThread("你");
myThread she=new myThread("她");
Thread t1=new Thread(you); //产生Thread类的对象t1
Thread t2=new Thread(she); //产生Thread类的对象t2
t1.start(); //注意用t1激活线程
t2.start(); //注意用t2激活线程
}
}

//app11_3.java 线程中join()方法的使用
//将app11_1的myThread类放在此处
public class app11_3
{
public static void main(String[] args)
{
myThread you=new myThread("你");
myThread she=new myThread("她");
you.start(); //激活you线程
try{
you.join(); //限制you线程结束后才能往下执行
}
catch(InterruptedException e) {}
she.start();
try{
she.join(); //限制she线程结束后才能往下执行
}
catch(InterruptedException e) {}
System.out.println("主方法main()运行结束!");
}
}

//app11_4.java
class Threadsale extends Thread //创建一个Thread子类,模拟航班售票窗口
{
private int tickets=10; //机票数
public void run()
{
while(true)
{
if(tickets>0) //如果有票可售
System.out.println(getName()+" 售机票第"+tickets--+"号");
else
System.exit(0);
}
}
}

public class app11_4 //再创建另一个类,在它的main()方法中创建并启动3个线程对象
{
public static void main(String[] args)
{
Threadsale t1=new Threadsale(); //创建三个Thread类的子类的对象
Threadsale t2=new Threadsale();
Threadsale t3=new Threadsale();
t1.start(); //分别用这三个对象调用自己的线程
t2.start();
t3.start();
}
}

// app11_5.java
class Threadsale implements Runnable //创建Runnable接口类,模拟航班售票窗口
{
private int tickets=10;
public void run()
{
while(true)
{
if(tickets>0)
System.out.println(Thread.currentThread().getName()+"售机票第"+tickets--+"号");
else
System.exit(0);
}
}
}
public class app11_5 //再构造另一个类,在它的main()方法中创建并启动3个线程对象
{
public static void main(String[] args)
{
Threadsale t=new Threadsale(); //只创建一个实现Runnable接口的售票类对象t
Thread t1=new Thread(t, "第1售票窗口"); //用此对象t作为参数创建3个线程,第
Thread t2=new Thread(t, "第2售票窗口"); //二个参数为线程名
Thread t3=new Thread(t, "第3售票窗口");
t1.start();
t2.start();
t3.start();
}
}

//app11_6.java
class Mbank //模拟银行帐户类
{
private static int sum=2000;
public static void take(int k)
{
int temp=sum;
temp-=k;
try{Thread.sleep((int)(1000*Math.random()));}
catch(InterruptedException e){ }
sum=temp;
System.out.println("sum="+sum);
}
}
class Customer extends Thread //模拟用户取款的线程类
{
public void run()
{
for(int i=1;i<=4;i++)
Mbank.take(100);
}
}
public class app11_6 //调用线程的主类
{
public static void main(String[] args)
{
Customer c1=new Customer();
Customer c2=new Customer();
c1.start();
c2.start();
}
}

//app11_7.java
class Mbank //模拟银行帐户类
{
private static int sum=2000;
public synchronized static void take(int k) //限定take()为同步方法
{
int temp=sum;
temp-=k;
try{Thread.sleep((int)(1000*Math.random()));}
catch(InterruptedException e){ }
sum=temp;
System.out.println("sum="+sum);
}
}
class Customer extends Thread //模拟用户取款的线程类
{
public void run()
{
for(int i=1;i<=4;i++)
Mbank.take(100);
}
}
public class app11_7 //调用线程的主类
{
public static void main(String[] args)
{
Customer c1=new Customer();
Customer c2=new Customer();
c1.start();
c2.start();
}
}

// app11_8.java
public class app11_8
{
public static void main(String[] args)
{
Tickets t=new Tickets(10); //新建一个票类对象,总票数作为参数
new Producer(t).start(); //以票类对象为参数创建存票线程对象,并启动
new Consumer(t).start(); //以同一票类对象为参数创建售票线程对象,并启动
}
}
class Tickets //票类
{
int size; //总票数
int number=0; //票号
boolean available=false; //表示当前是否有票可售
public Tickets(int size) //构造方法,传入总票数参数
{
this.size=size;
}
public synchronized void put() //同步方法,实现存票功能
{
if(available) //如果还有存票待售,则存票线程等待
try{wait(); }
catch(Exception e){ }
System.out.println("存入第【"+(++number)+ "】号票");
available=true;
notify(); //存票后唤醒售票线程开始售票
}
public synchronized void sell() //同步方法,实现售票功能
{
if(!available) //如果没有存票,则售票线程等待
try{wait(); }
catch(Exception e){ }
System.out.println("售出第【"+(number) + "】号票");
available=false;
notify(); //售票后唤醒存票线程开始存票
if(number==size) number=size+1; //在售完最后一张票后,设置一个结束标志
//number>size表示售票结束
}
}
class Producer extends Thread
{
Tickets t=null;
public Producer(Tickets t) //构造方法,使两线程共享票类对象
{
this.t=t;
}
public void run()
{
while(t.number<t.size)
t.put();
}
}
class Consumer extends Thread
{
Tickets t=null;
public Consumer(Tickets t)
{
this.t=t;
}
public void run()
{
while(t.number<=t.size)
t.sell();
}
}

//app12_1.java
import java.awt.*; //加载java.awt类库里的所有类
public class app12_1
{
static Frame frm=new Frame("这是个AWT程序"); //创建类静态框架并设置标题
public static void main(String[] args)
{
Label lab=new Label("我是一个标签"); //创建一个标签对象lab
frm.setSize(180,140); //设置框架大小
frm.setBackground(Color.yellow); //设置框架背景颜色
frm.setLocation(250,150); //设置窗口的位置
frm.add(lab); //将标签对象lab加入窗口中
frm.setVisible(true); //将窗口显示出来
}
}

//app12_2.java
import java.awt.*; //加载java.awt类库里的所有类
public class app12_2
{
public static void main(String[] args)
{
Frame frm=new Frame("我的框架");
frm.setSize(300,200);
frm.setLocation(500,400);
frm.setBackground(Color.lightGray);
Panel pan=new Panel();
pan.setSize(150,100);
pan.setLocation(50,50);
pan.setBackground(Color.green);
Button bun=new Button("点击我");
bun.setSize(80,20);
bun.setLocation(50,50);
bun.setBackground(Color.yellow);
frm.setLayout(null); //取消frm的默认布局管理器
pan.setLayout(null); //取消pan的默认布局管理器
pan.add(bun); //将命令按钮加入到面板中
frm.add(pan); //将面板加入到窗口中
frm.setVisible(true);
}
}

//app12_3.java 在窗口加入标签对象
import java.awt.*;
public class app12_3
{
static Frame frm=new Frame("标签类窗口");
static Label lab=new Label(); //创建标签对象
public static void main(String[] args)
{
frm.setSize(300,200);
frm.setBackground(Color.pink); //设置窗口底色的粉红色
lab.setText("我是一个标签"); //设置标签显示的文字
lab.setAlignment(Label.CENTER); //将标签内的文字居中
lab.setBackground(Color.yellow); //设置标签的底色为黄色
lab.setForeground(Color.red); //设置标签上的文字为红色
Font fnt=new Font("Serief",Font.BOLD+Font.ITALIC,20);
lab.setFont(fnt); //设置标签上字体的样式
frm.add(lab); //将标签加入到窗口中
frm.setVisible(true);
}
}

//app12_4.java 指定标签对象的大小
import java.awt.*;
public class app12_4
{
static Frame frm=new Frame("标签类窗口");
static Label lab=new Label(); //创建标签对象
public static void main(String[] args)
{
frm.setLayout(null); //取消页面设置
frm.setSize(300,200);
frm.setBackground(Color.pink);
lab.setText("我是一个标签");
lab.setAlignment(Label.CENTER);
lab.setBackground(Color.yellow);
lab.setForeground(Color.red);
lab.setLocation(120,90);
lab.setSize(130,30);
Font fnt=new Font("Serief",Font.BOLD+Font.ITALIC,20);
lab.setFont(fnt);
frm.add(lab);
frm.setVisible(true);
}
}

//app12_5.java 设置命令按钮
import java.awt.*;
public class app12_5 extends Frame //指定app12_5继承自Frame类
{
public static void main(String[] args)
{
app12_5 frm=new app12_5(); //用app12_5类产生frm对象
Button btn=new Button("确定"); //创建按钮对象
frm.setLayout(null); //取消页面设置
frm.setSize(300,200);
frm.setTitle("按钮类窗口");
btn.setBounds(50,70,100,40); //设置按钮的大小与位置
frm.add(btn);
frm.setVisible(true);
}
}

//app12_6.java 设置文本框和文本区
import java.awt.*;
public class app12_6 extends Frame
{
TextField tf1=new TextField("该文本框不可编辑",20);
static TextField tf2=new TextField("口令输入框",20);
public app12_6(String str) //构造方法
{
super(str); //调用父类Frame的构造方法
tf1.setBounds(20,60,120,20);
tf1.setEditable(false); //设置文本框对象tf1为不可编辑
add(tf1); //将文本框对象tf1加入到窗口中
}
public static void main(String[] args)
{
app12_6 frm=new app12_6("文本编辑功能"); //调用app12_6类构造方法
TextArea ta=new TextArea ("您好",10,20,TextArea. SCROLLBARS_VERTICAL_ONLY);
frm.setLocation(200,150);
frm.setSize(240,220);
frm.setLayout(null); //取消页面设置
tf2.setBounds(20,30,120,20);
tf2.setEchoChar('*'); //设置文本框对象tf2的回显字符为“*”
ta.setBounds(20,90,140,100);
frm.add(tf2);
frm.add(ta);
System.out.println(tf2.getText());
frm.setVisible(true);
}
}

//app12_7.java 设置复选框和单选按钮组
import java.awt.*;
public class app12_7 extends Frame
{
static Frame frm=new Frame("复选框和单选按钮组选取框");
static Checkbox chk1=new Checkbox("租体",true); //设置chk1为选中状态
static Checkbox chk2=new Checkbox("斜体");
static Checkbox chk3=new Checkbox("下划线");
static Checkbox chk_g1=new Checkbox("红色");
static Checkbox chk_g2=new Checkbox("绿色",true); //设置chk_g2为选中状态
static Checkbox chk_g3=new Checkbox("蓝色");
public static void main(String[] args)
{
CheckboxGroup grp=new CheckboxGroup(); //创建一个单选按钮组对象
frm.setLocation(200,150);
frm.setSize(250,220);
frm.setLayout(null); //取消页面设置
chk1.setBounds(20,30,120,20); //设置复选框的位置和大小
chk2.setBounds(20,50,120,20);
chk3.setBounds(20,70,120,20);
chk_g1.setBounds(20,90,120,20);
chk_g2.setBounds(20,110,120,20);
chk_g3.setBounds(20,130,120,20);
chk_g1.setCheckboxGroup(grp); //将chk_g1加入grp组中
chk_g2.setCheckboxGroup(grp);
chk_g3.setCheckboxGroup(grp);
frm.add(chk1);
frm.add(chk2);
frm.add(chk3);
frm.add(chk_g1);
frm.add(chk_g2);
frm.add(chk_g3);
frm.setVisible(true);
}
}

//app12_8.java FlowLayout类的使用
import java.awt.*;
public class app12_8 extends Frame
{
static Frame frm=new Frame("流式布局设置管理器FlowLayout");
public static void main(String[] args)
{
FlowLayout flow=new FlowLayout (FlowLayout.CENTER,5,10);
Button but=new Button("按钮");
Label lab=new Label("我是一个标签");
frm.setLayout(flow); //设置页面布局为流式布局方式
frm.setSize(200,150);
frm.setBackground(Color.PINK); //设置窗口背景为粉红色
frm.add(but); //添加命令按钮组件
frm.add(lab); //添加标签组件
frm.add(new TextField("流式布局策略FlowLayout",18)); //添加文本框组件
frm.setVisible(true);
}
}

//app12_9.java BorderLayout类的使用
import java.awt.*;
public class app12_9 extends Frame
{
static Frame frm=new Frame("边界式布局管理器BorderLayout");
public static void main(String[] args)
{
BorderLayout border=new BorderLayout (5,10);
frm.setLayout(border); //设置页面布局为边界式布局方式
frm.setSize(280,200);
frm.add(new Button("上北"), BorderLayout.NORTH);
frm.add(new Button("下南"), BorderLayout. SOUTH);
frm.add(new Button("左西"), BorderLayout.WEST);
frm.add(new Button("右东"), BorderLayout.EAST);
frm.add(new Button("中央"), BorderLayout.CENTER);
frm.setVisible(true);
}
}

//app12_10.java CardLayout类的使用
import java.awt.*;
public class app12_10 extends Frame
{
static Frame frm=new Frame("卡片式布局设置管理器CardLayout");
static Panel pan1=new Panel(); //创建面板对象
static Panel pan2=new Panel();
public static void main(String[] args)
{
frm.setLayout(null); //取消窗口的页面设置
pan2.setLayout(new GridLayout(1,4)); //将面板对象设置为1行4列的布局
CardLayout crd=new CardLayout (5,10); //创建卡片式布局对象crd
pan1.setLayout(crd); //将面板pan1设置为卡片式布局方式
frm.setSize(300,250);
frm.setResizable(false);
pan1.setBounds(10,20,270,200);
pan2.setBounds(10,220,270, 20);
frm.add(pan1); //将面板添加到窗口里
frm.add(pan2) ;
Label lab1=new Label("第一页", Label.CENTER);
TextField tex=new TextField("卡片式布局策略CardLayout",18);
pan1.add(lab1, "c1"); //将标签组件lab1命名为c1后加入到面板中
pan1.add(new Label("第二页", Label.CENTER), "c2");
pan1.add(tex, "t1"); //将文本框组件tex命名为t1后加入到面板中
crd.show(pan1, "t1"); //将pan1中的tex组件显示在容器中
pan2.add(new Button("第一页"), "1");
pan2.add(new Button("上一页"),"2");
pan2.add(new Button("下一页"),"3");
pan2.add(new Button("最后页"),"4");
frm.setVisible(true);
}
}

//app12_11.java GridLayout类的使用
import java.awt.*;
public class app12_11 extends Frame
{
static Panel pan=new Panel(); //创建一个面板对象pan
static Label lab=new Label("0. ",Label.RIGHT); //创建标签lab,文字右对齐
static Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,bp,ba,bs,bm,bd,be;
public static void main(String[] args)
{
app12_11 frm=new app12_11();
b0=new Button("0"); b1=new Button("1"); b2=new Button("2");
b3=new Button("3"); b4=new Button("4"); b5=new Button("5");
b6=new Button("6"); b7=new Button("7"); b8=new Button("8");
b9=new Button("9"); bp=new Button("."); ba=new Button("+");
bs=new Button("-"); bm=new Button("*"); bd=new Button("/");
be=new Button("=");
frm.setTitle("网格式布局管理器GridLayout");
frm.setLayout(null); //取消窗口的页面设置
frm.setSize(260,200);
frm.setResizable(false); //设置窗口的大小为不可改变
GridLayout grid=new GridLayout (4,4); //创建4行4列的页面配置
pan.setLayout(grid); //将面板对象pan的布局策略设为网格布局方式
pan.setBounds(20,60,150,120);
lab.setBounds(20,35,150,20);
lab.setBackground(Color.cyan); //设置标签的颜色
pan.add(b7); pan.add(b8); pan.add(b9); pan.add(bd);
pan.add(b4); pan.add(b5); pan.add(b6); pan.add(bm);
pan.add(b1); pan.add(b2); pan.add(b3); pan.add(bs);
pan.add(b0); pan.add(bp); pan.add(be); pan.add(ba);
frm.add(lab);
frm.add(pan);
frm.setVisible(true);
}
}

//app13_1.java 简单的事件处理程序(未加入事件处理)
import java.awt.*;
public class app13_1 extends Frame //设置app13_1类继承自Frame类
{
static app13_1 frm=new app13_1(); //创建app13_1类的对象frm
static Button bt=new Button("设置字体颜色");
static TextArea ta =new TextArea ("字体颜色",5,20);
public static void main(String[] args)
{
frm.setTitle("操作事件");
frm.setLayout(new FlowLayout());
frm.setSize(260,170);
frm.add(ta);
frm.add(bt);
frm.setVisible(true);
}
}

//app13_1.java 简单的事件处理程序(已加入事件处理)
import java.awt.*;
import java.awt.event.*;
public class app13_1 extends Frame implements ActionListener
{
static app13_1 frm=new app13_1();
static Button bt=new Button("设置字体颜色");
static TextArea ta =new TextArea ("字体颜色",5,20);
public static void main(String[] args)
{
bt.addActionListener(frm); //把监听者frm向事件源bt注册
frm.setTitle("操作事件");
frm.setLayout(new FlowLayout());
frm.setSize(260,170);
frm.add(ta);
frm.add(bt);
frm.setVisible(true);
}
public void actionPerformed(ActionEvent e) //事件发生时的处理操作
{
ta.setForeground(Color.red); //把文本区内的文字设置为红色
}
}

//app13_2.java 定义内部类充当监听者
import java.awt.*;
import java.awt.event.*;
public class app13_2 //定义主类,注意此类不用继承Frame类
{
static Frame frm=new Frame("操作事件");
static Button bt=new Button("设置字体颜色");
static TextArea ta =new TextArea ("字体颜色",5,20);
public static void main(String[] args)
{
bt.addActionListener(new MyActLister()); //创建内部类对象充当监听者,并向事件源bt注册
frm.setLayout(new FlowLayout());
frm.setSize(260,170);
frm.add(ta);
frm.add(bt);
frm.setVisible(true);
}
//定义内部类MyActLister,并实现ActionListener接口
static class MyActLister implements ActionListener
{
public void actionPerformed(ActionEvent e) //事件发生时的处理操作
{
ta.setForeground(Color.red); //把文本区内的文字设置为红色
}
}
}

//app13_3.java 命令按钮功能的实现
import java.awt.*;
import java.awt.event.*;
public class app13_3 extends Frame implements ActionListener
{
static app13_3 frm=new app13_3();
static Panel pan1=new Panel();
static Panel pan2=new Panel();
static Button but1= new Button("第一页");
static Button but2= new Button("上一页");
static Button but3= new Button("下一页");
static Button but4= new Button("最后页");
static CardLayout crd=new CardLayout (5,10); //需将crd定义为static类型
public static void main(String[] args)
{
frm.setLayout(null);
frm.setTitle("操作事件");
pan2.setLayout(new GridLayout(1,4));
pan1.setLayout(crd);
frm.setSize(300,250);
frm.setResizable(false);
but1.addActionListener(frm); //把事件监听者frm向but1注册
but2.addActionListener(frm); //把事件监听者frm向but2注册
but3.addActionListener(frm); //把事件监听者frm向but3注册
but4.addActionListener(frm); //把事件监听者frm向but4注册
pan1.setBounds(10,20,270,200);
pan2.setBounds(10,220,270, 20);
frm.add(pan1);
frm.add(pan2) ;
Label lab1=new Label("第一页", Label.CENTER);
TextField tex=new TextField("卡片式布局策略CardLayout",18);
pan1.add(lab1, "n1");
pan1.add(new Label("第二页", Label.CENTER), "n2");
pan1.add(tex, "n3");
crd.show(pan1, "n3");
pan2.add(but1, "d1");
pan2.add(but2, "d2");
pan2.add(but3, "d3");
pan2.add(but4, "d4");
frm.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Button but=(Button)e.getSource(); //获得事件源并强制将其转换成Button类型
if(but==but1) crd.first(pan1); //单击的是but1按钮,则显示第一张卡片
else if(but==but2) crd.previous(pan1);
else if(but==but3) crd.next(pan1);
else crd.last(pan1);
}
}

//app13_4.java 选项事件类的应用
import java.awt.*;
import java.awt.event.*;
public class app13_4 extends Frame implements ItemListener
{
static app13_4 frm=new app13_4();
static Checkbox chk1=new Checkbox("租体");
static Checkbox chk2=new Checkbox("斜体");
static Checkbox chk_g1=new Checkbox("红色");
static Checkbox chk_g2=new Checkbox("蓝色");
static TextArea ta=new TextArea ("选项事件类ItemEvent的使用方法",8,30);
public static void main(String[] args)
{
CheckboxGroup grp=new CheckboxGroup(); //创建一个单按钮组对象
frm.setTitle("选项事件处理");
frm.setLocation(200,150);
frm.setSize(250,220);
frm.setLayout(new FlowLayout(FlowLayout.LEFT));
chk_g1.setCheckboxGroup(grp); //将chk_g1设置为单选按钮
chk_g2.setCheckboxGroup(grp);
chk1. addItemListener(frm); //设置frm为chk1的监听者
chk2. addItemListener(frm); //设置frm为chk2的监听者
chk_g1.addItemListener(frm); //设置frm为chk_g1的监听者
chk_g2.addItemListener(frm); //设置frm为chk_g2的监听者
frm.add(chk1);
frm.add(chk2);
frm.add(chk_g1);
frm.add(chk_g2);
frm.add(ta);
frm.setVisible(true);
}
//ItemEvent事件发生时的处理操作
public void itemStateChanged(ItemEvent e)
{
Checkbox chk=(Checkbox)e.getSource(); //获得事件源
Font font1=ta.getFont();
int style1=font1.getStyle();
if(chk==chk_g1) ta.setForeground(Color.RED);
else if(chk==chk_g2) ta.setForeground(Color. BLUE);
else if((chk==chk1)||( chk==chk2))
{
if(chk==chk1) style1=style1^1; //按位异或运算^
if(chk==chk2) style1=style1^2;
ta.setFont(new Font(font1.getName(),style1,font1.getSize()));
ta.append("\nstyle="+style1+" "+e.getItem()+" " +chk.getState());
}
}
}

//app13_5.java 文本事件类TextEvent的应用
import java.awt.*;
import java.awt.event.*;
public class app13_5 extends Frame //定义主类
{
static TextArea ta1=new TextArea ("",6,10, TextArea.SCROLLBARS_NONE);
static TextArea ta2=new TextArea ("",6,10, TextArea.SCROLLBARS_NONE);
public static void main(String[] args)
{
app13_5 frm=new app13_5(); //调用构造方法
frm.setTitle("文本事件处理TextEvent");
frm.setSize(220,150);
frm.setLayout(new FlowLayout(FlowLayout.CENTER));
frm.setVisible(true);
}
public app13_5() //构造方法
{
ta1.addTextListener(new MyTxListener());
add(ta1);
add(ta2);
ta2.setEditable(false);
}
class MyTxListener implements TextListener //定义内部类实现TextListener接口
{
public void textValueChanged(TextEvent e) //事件发生时的处理操作
{
String text=ta1.getText(); //获得ta1的内容
ta2.setText(text); //将ta1的内容放入到ta2中
}
}
}

//app13_6.java 窗口事件类WindowEvent的应用
import java.awt.*;
import java.awt.event.*;
public class app13_6 extends Frame //定义主类
{
static Label lab=new Label();
static app13_6 frm=new app13_6();
static MyWinListener winlist= new MyWinListener();
public static void main(String[] args)
{
frm.setLayout(null); //取消页面设置
frm.setTitle("窗口事件");
frm.setBounds(120,50,215,100);
lab.setBounds(25,25,150,50);
frm.add(lab);
frm.addWindowListener(winlist); //设置winlist为frm的事件监听者
frm.setVisible(true);
}
//定义静态内部类MyWinListener并实现WindowListener接口
static class MyWinListener implements WindowListener
{
public void windowOpened(WindowEvent e) //打开窗口时的处理操作
{ lab.setText("打开新窗口"); }
public void windowActivated(WindowEvent e) //激活窗口时的处理操作
{ lab.setText("窗口被激活"); }
public void windowIconified(WindowEvent e) //窗口最小化时的处理操作
{ frm.setTitle("窗口被最小化"); }
public void windowDeiconified(WindowEvent e) //还原窗口时的处理操作
{ frm.setTitle("窗口被还原成正常大小"); }
public void windowClosing(WindowEvent e) //关闭窗口时的处理操作
{
frm.dispose(); //关闭窗口并释放资源
System.exit(0); //程序正常结束
}
public void windowDeactivated(WindowEvent e) //窗口失活时的处理操作
{ } //空操作
public void windowClosed(WindowEvent e) //窗口关闭后的处理操作
{ } //空操作
}
}

//app13_7.java 用KeyListener接口处理KeyEvent事件
import java.awt.*;
import java.awt.event.*;
public class app13_7 extends Frame implements KeyListener
{
static TextField tf=new TextField(20);
static TextArea ta=new TextArea(6,20);
public static void main(String[] args)
{
app13_7 frm=new app13_7();
frm.setLayout(null);
frm.setTitle("按键事件");
frm.setBounds(100,100,240,150);
tf.setBounds(20, 30,200,20);
ta.setBounds(20, 55,200,80);
ta.setEnabled(false); //设置文本区为禁用状态
frm.add(tf);
frm.add(ta);
tf.addKeyListener(frm); //设置frm为事件监听者并向tf组件注册
frm.setVisible(true);
}
public void keyPressed(KeyEvent e) //按下按键时的处理操作
{
if(e.isActionKey()) ta.append("您按的是Action键\n");
else ta.setText ("keyPressed事件发生,您按了【"+e.getKeyChar()+"】键\n");
}
public void keyReleased(KeyEvent e) //放开按键时的处理操作
{ ta. append("您现在放开了按键\n"); }
public void keyTyped(KeyEvent e) //输入字符时的处理操作
{
String input=tf.getText()+e.getKeyChar(); //取得tf中输入的内容
if(e.getKeyChar()=='\n') ta.setText(input); //按Enter键后设定ta的内容
}
}

//app13_8.java 用适配器类KeyAdapyer处理KeyEvent事件
import java.awt.*;
import java.awt.event.*;
public class app13_8 extends Frame
{
static TextField tf=new TextField(20);
static TextArea ta=new TextArea(6,20);
public static void main(String[] args)
{
app13_8 frm=new app13_8();
frm.setLayout(null);
frm.setTitle("按键事件");
frm.setBounds(100,100,240,150);
tf.setBounds(20, 30,200,20);
ta.setBounds(20, 55,200,80);
ta.setEnabled(false); //设置文本区为禁用状态
frm.add(tf);
frm.add(ta);
tf.addKeyListener(new MyKeyList());
frm.setVisible(true);
}
//定义静态内部类MyKeyList,并继承自KeyAdapter
static class MyKeyList extends KeyAdapter
{
public void keyTyped(KeyEvent e) //输入字符时的处理操作
{
String input=tf.getText()+e.getKeyChar();
if(e.getKeyChar()=='\n') ta.setText(input);
}
}
}

//app13_9.java 鼠标事件的处理
import java.awt.*;
import java.awt.event.*;
public class app13_9 extends Frame
{
static TextField tf=new TextField(20);
static Button bun=new Button("拖动我");
static int px,py,ox,oy,offx,offy,x,y;
public static void main(String[] args)
{
app13_9 frm=new app13_9();
frm.setLayout(null);
frm.setTitle("鼠标事件的处理");
frm.setBounds(10,10,330,240);
tf.setBounds(60,200,200,20);
bun.setBounds(60,50,50,25);
tf.setEditable(false); //设置文本框为不可编辑状态
frm.add(tf);
frm.add(bun);
bun.addMouseMotionListener(new MyMouseMotionList ()); //设置监听者
bun.addMouseListener(new MyMouseList()); //设置监听者
frm.setVisible(true);
}
//定义静态内部类MyMouseList,并继承自MouseAdapter
static class MyMouseList extends MouseAdapter
{
public void mousePressed(MouseEvent?e) //鼠标按钮被按下时的处理操作
{
px= e.getX(); //取得鼠标按下时的x坐标
py= e.getY(); //取得鼠标按下时的y坐标
ox=bun.getLocation().x; //取得bun的左边界距窗口左边界的距离
oy=bun.getLocation().y; //取得bun的上边界距窗口上边界的距离
}
}
//定义静态内部类MyMouseMotionList,并继承自MouseMotionAdapter
static class MyMouseMotionList extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent?e) //用鼠标拖动事件源的处理操作
{
offx=px-ox; //offx为鼠标指针与命令按钮左边界的距离
offy=py-oy; //offy为鼠标指针与命令按钮上边界的距离
x= e.getX()-offx;
y= e.getY()-offy;
String position="命令按钮放置在("+ x+","+y+")的位置";
tf.setText(position);
bun.setLocation(x,y); //将命令按钮放置在(x,y)的位置
ox=x; //更新命令按钮左边缘的位置
oy=y; //更新命令按钮上边缘的位置
}
}
}

//app13_10.java 列表框控件的应用
import java.awt.*;
import java.awt.event.*;
public class app13_10 extends Frame implements ItemListener,ActionListener
{
static app13_10 frm=new app13_10();
static List lst=new List(); //创建列表框对象lst
static TextArea ta=new TextArea(5,20);
public static void main(String[] args)
{
frm.setLayout(new FlowLayout(FlowLayout.CENTER,10,20));
frm.setSize(350,200);
lst.add("红色"); //将选项加入到列表框中
lst.add("绿色");
lst.add("蓝色");
lst.add("黄色");
lst.addItemListener(frm); //设置frm为lst的监听者
lst.addActionListener(frm);
frm.add(lst); //将列表对象lst加入窗口中
frm.add(ta);
frm.setVisible(true);
}
public void itemStateChanged(ItemEvent e) //处理单击事件的程序代码
{
String clr=lst.getSelectedItem(); //取得被选中选项的名称
if(clr=="红色")
ta.setBackground(Color.red);
else if(clr=="绿色")
ta.setBackground(Color.green);
else if(clr=="蓝色")
ta.setBackground(Color.blue);
else if(clr=="黄色")
ta.setBackground(Color.yellow);
frm.setTitle("您选择了【"+clr+"】颜色"); //设置窗口的标题
}
public void actionPerformed(ActionEvent e) //处理双击事件的程序代码
{
String clrn=lst.getSelectedItem(); //取得被选中选项的名称
clrn="您双击的是【"+clrn+"】\n";
ta.append(clrn); //将字符串clrn添加到文本区中
}
}

//app13_11.java 下拉列表框控件的应用
import java.awt.*;
import java.awt.event.*;
public class app13_11 extends Frame
{
static app13_11 frm=new app13_11();
static Choice cho=new Choice(); //创建下拉列表框对象cho
static TextArea ta=new TextArea(5,15);
public static void main(String[] args)
{
frm.setLayout(new FlowLayout(FlowLayout.CENTER,10,20));
frm.setSize(250,170);
cho.add("红色"); //将选项加入到下拉列表框中
cho.add("绿色");
cho.add("蓝色");
cho.add("黄色");
cho.addItemListener(new MyItemListener()); //设置内部类对象为cho的监听者
frm.add(cho); //将下拉列表对象cho加入窗口中
frm.add(ta);
frm.setVisible(true);
}
static class MyItemListener implements ItemListener
{
public void itemStateChanged(ItemEvent e) //处理单击事件的程序代码
{
String clr=cho.getSelectedItem(); //取得被选中选项的名称
if(clr=="红色")
ta.setBackground(Color.red);
else if(clr=="绿色")
ta.setBackground(Color.green);
else if(clr=="蓝色")
ta.setBackground(Color.blue);
else if(clr=="黄色")
ta.setBackground(Color.yellow);
frm.setTitle("您选择了【"+clr+"】颜色");
ta.setText(clr); //将选中的选项名称添加到文本区中
}
}
}

//app13_12.java 菜单栏设计及相应的事件处理
import java.awt.*;
import java.awt.event.*;
public class app13_12 extends Frame implements ActionListener,ItemListener
{
static app13_12 frm=new app13_12();
static MenuBar mb=new MenuBar(); //创建MenuBar对象mb
static Menu m1=new Menu("颜色"); //创建Menu对象m1
static Menu m2=new Menu("窗口"); //创建Menu对象m2
static MenuItem mi1=new MenuItem("红色"); //创建MenuItem对象mi1
static MenuItem mi2=new MenuItem("绿色");
static MenuItem mi3=new MenuItem("蓝色");
static MenuItem mi4=new MenuItem("关闭");
static CheckboxMenuItem cbmi=new CheckboxMenuItem("斜体"); //复选框菜单项
static PopupMenu pm=new PopupMenu("弹出式菜单"); //创建弹出式菜单
static MenuItem Pop_m1,Pop_m2,Pop_m3; //弹出菜单项
static TextArea ta=new TextArea ("菜单程序设计",10,30);
public static void main(String[] args)
{
frm.setLayout(null); //取消页面设置
frm.setLocation(100,80);
frm.setSize(260,170);
frm.add(ta);
ta.setBounds(40,65,180,80);
mb.add(m1); //将m1加入到mb中
mb.add(m2);
m1.add(mi1); //将mi1加入到m1中
m1.add(mi2);
m1.add(mi3);
m1.addSeparator(); //加一分隔线
m1.add(cbmi); //添加带复选框的菜单项
m2.add(mi4); //将mi4加入到m2中
frm.setMenuBar(mb); //设置frm的菜单栏为mb
Pop_m1= new MenuItem("红色");
Pop_m2= new MenuItem("绿色");
Pop_m3= new MenuItem("蓝色");
pm.add(Pop_m1); //向弹出式菜单中添加菜单项
pm.add(Pop_m2);
pm.add(Pop_m3);
Pop_m1.addActionListener(frm); //设置frm为弹出菜单项的监听者
Pop_m2.addActionListener(frm);
Pop_m3.addActionListener(frm);
frm.add(pm); //将弹出式菜单附加在frm上
ta.addMouseListener (new MyMouseList()); //设置内部类为ta的监听者
mi1.addActionListener(frm); //设置frm为mi1的事件监听者
mi2.addActionListener(frm);
mi3.addActionListener(frm);
cbmi.addItemListener(frm); //设置frm为带复选框菜单项的监听者
mi4.addActionListener(frm);
frm.setVisible(true);
}
public void actionPerformed(ActionEvent e) //事件处理的程序代码
{
MenuItem mi=(MenuItem)e.getSource(); //取得引发事件的对象
String miLab=mi.getLabel(); //取得菜单项的文字标题
if(miLab=="红色")
ta.setForeground(Color.red);
else if(miLab=="绿色")
ta.setForeground (Color.green);
else if(miLab=="蓝色")
ta.setForeground (Color.blue);
else if(mi==mi4)
frm.dispose(); //关闭窗口,释放资源
frm.setTitle("设置文字颜色为【"+miLab+"】");
}
public void itemStateChanged(ItemEvent ie) //处理复选框菜单项的方法
{
boolean yn= cbmi.getState();
if (yn) ta.setFont(new Font("楷体_GB2312",Font.ITALIC,15));
else ta.setFont(new Font("宋体",Font.PLAIN,15));
}
static class MyMouseList extends MouseAdapter //处理鼠标事件的类
{
public void mouseReleased(MouseEvent mce) //释放鼠标时触发的事件
{
if (mce.isPopupTrigger()) //判断鼠标事件是否是由弹出菜单引发
pm.show((Component)mce.getSource(),mce.getX(),mce.getY());
}
}
}

//app13_13.java 滚动条组件及相应的事件处理
import java.awt.*;
import java.awt.event.*;
public class app13_13 extends Frame implements AdjustmentListener
{
static app13_13 frm=new app13_13();
static Scrollbar sbR=new Scrollbar(Scrollbar.VERTICAL); //建垂直滚动条
static Scrollbar sbG=new Scrollbar(Scrollbar.HORIZONTAL); //建水平滚动条
static Scrollbar sbB=new Scrollbar(Scrollbar.VERTICAL);
public static void main(String[] args)
{
BorderLayout br=new BorderLayout(5,5);
frm.setSize(280,150);
frm.add(sbR,br.WEST); //设置调整红色的滚动条
frm.add(sbG,br.SOUTH); //设置调整绿色的滚动条
frm.add(sbB,br.EAST); //设置调整蓝色的滚动条
sbR.setValues(255,45,0,300); //设置滚动条的相关参数
sbG.setValues(255,45,0,300);
sbB.setValues(255,45,0,300);
sbR.addAdjustmentListener(frm); //设置frm为sbR的监听者
sbG.addAdjustmentListener(frm);
sbB.addAdjustmentListener(frm);
frm.setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent?e)
{
int colorR=sbR.getValue(); //取得滚动条sbR的值
int colorG=sbG.getValue(); //取得滚动条sbG的值
int colorB=sbB.getValue(); //取得滚动条sbB的值
frm.setTitle("红,绿,蓝=("+colorR+","+colorG+","+colorB+")");
frm.setBackground(new Color(colorR,colorG,colorB));
}
}

//app13_14.java 对话框组件及相应的事件处理
import java.awt.*;
import java.awt.event.*;
public class app13_14 extends Frame implements ActionListener
{
static app13_14 frm=new app13_14();
static Dialog diag=new Dialog(frm); //创建隶属于frm的对话框diag
static Button bt_close=new Button("关闭");
static Button bt_cancel=new Button("取消");
static MyWinList wlist=new MyWinList(); //创建监听者对象wlist
public static void main(String[] args)
{
frm.setTitle("对话框的应用");
frm.setSize(250,150);
diag.setTitle("请选择"); //设置对话框的标题
diag.setSize(150,100); //设置对话框的大小
diag.setLayout(new FlowLayout(FlowLayout.CENTER,5,20));
diag.add(bt_close);
diag.add(bt_cancel);
bt_close.addActionListener(frm); //设置按钮的监听者为frm
bt_cancel.addActionListener(frm);
frm.addWindowListener(wlist); //设置内部类对象wlist为frm的监听者
frm.setVisible(true);
}
static class MyWinList extends WindowAdapter
{
public void windowClosing(WindowEvent e) //按窗口右上角关闭按钮时的操作
{
diag.setLocation(70,35); //设置对话框的位置
diag. setVisible (true); //显示对话框
}
}
public void actionPerformed(ActionEvent?e) //按对话框中按钮时的处理操作
{
Button bt=(Button)e.getSource(); //获取被单击的按钮
if (bt==bt_close) //若单击的是“关闭”按钮
{
diag.dispose(); //关闭对话框
frm.dispose(); //关闭窗口
}
else if (bt==bt_cancel) //若单击的是“取消”按钮
diag. setVisible (false); //隐藏对话框
}
}

//app13_15.java 文件对话框的应用
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class app13_15 extends Frame implements ActionListener
{
static app13_15 frm=new app13_15();
static FileDialog ofd=new FileDialog(frm, "打开"); //创建文件对话框ofd
static FileDialog sfd=new FileDialog(frm, "保存", FileDialog.SAVE);
static TextArea ta=new TextArea(8,30);
static Button fbt_open=new Button("选取");
static Button fbt_save=new Button("存盘");
public static void main(String[] args)
{
frm.setTitle("文件对话框的应用");
frm.setSize(300,230);
frm.setLayout(new FlowLayout(FlowLayout.CENTER,15,10));
frm.add(ta); frm.add(fbt_open); frm.add(fbt_save);
fbt_open.addActionListener(frm); //设置窗口中按钮的监听者为frm
fbt_save. addActionListener(frm);
frm.setVisible(true);
}
public void actionPerformed(ActionEvent?e) //单击窗口中按钮时的处理操作
{
Button bt=(Button)e.getSource(); //获取被单击的按钮
if (bt==fbt_open) //若单击的是窗口中的“选取”按钮
{
ofd.setVisible(true); //显示文件打开对话框,并掌握主控权
String fname=ofd.getDirectory()+ofd.getFile(); //获取路径与文件名
try
{
FileInputStream fi=new FileInputStream(fname); //创建输入流
byte[] fc=new byte[fi.available()]; //以文件长度为大小定义数组
fi.read(fc); //将读取的内容写入到数组fc中
ta.setText(new String(fc)); //将数组fc中的内容显示在文本区ta内
fi.close();
}
catch(IOException ioe){};
}
else if(bt==fbt_save) //若单击的是窗口中的“存盘”按钮
{
sfd.setVisible(true); //显示文件保存对话框,并掌握主控权
String fname=sfd.getDirectory()+sfd.getFile(); //获取路径与文件名
try {
FileOutputStream fs=new FileOutputStream(fname); //创建输出流
fs.write(ta.getText().getBytes()); //将ta中的内容转换成字节后写入文件fs中
fs.close();
} catch(IOException ioe){};
}
}
}

//app14_1.java 简单的绘图程序
import java.awt.*;
import java.awt.event.*;
public class app14_1 extends Frame implements ActionListener
{
static app14_1 frm=new app14_1();
static Button bnt1 =new Button("画圆");
static Button bnt2 =new Button("画椭圆");
int circle=0;
public static void main(String[] args)
{
frm.setTitle("简单绘图应用程序");
frm.setSize(300,250);
frm.setLayout(null);
bnt1.setBounds(90, 215,50,25);
bnt2.setBounds(160,215,50,25);
frm.add(bnt1); frm.add(bnt2);
bnt1.addActionListener(frm);
bnt2.addActionListener(frm);
frm.setVisible(true);
}
public void actionPerformed(ActionEvent?e)
{
Button bt=(Button)e.getSource(); //获取被按下的按钮
if (bt==bnt1) circle=1; //若按下的是“画圆”按钮
else circle=2; //若按下的是“画椭圆”按钮
Graphics g=getGraphics(); //获取窗口的绘图区
paint(g);
}
public void paint(Graphics g)
{
g.setFont(new Font("楷体",Font.ITALIC,20)); //设置字体
g.setColor(Color.red); //设置颜色
g.drawString("画圆或椭圆",120,50); //以(120,50)为左下角显示字符串
if (circle==1) g.drawOval (100,90,70,70); //画圆
else if (circle==2) g.drawOval (80,60,70,120); //画椭圆
}
}

//app14_2.java 手工绘画程序
import java.awt.*;
import java.awt.event.*;
public class app14_2 extends Frame implements MouseMotionListener
{
static int x1,y1,x2,y2;
public static void main(String[] args)
{
app14_2 frm=new app14_2();
frm.setTitle("交互式绘图");
frm.setBounds(10,10,250,200);
frm.addMouseMotionListener(frm); //设置监听者
frm.addMouseListener(new MyMouseList()); //设置监听者
frm.setVisible(true);
}
//定义静态内部类MyMouseList,并继承自MouseAdapter
static class MyMouseList extends MouseAdapter
{
public void mousePressed(MouseEvent?e)
{
x1= e.getX(); //取得鼠标按下时的x坐标,作为起点的x坐标
y1= e.getY(); //取得鼠标按下时的y坐标,作为起点的y坐标
}
}
public void mouseDragged(MouseEvent?e) //用鼠标拖动事件源的处理操作
{
x2= e.getX(); //取得拖动鼠标时的x坐标
y2= e.getY(); //取得拖动鼠标时的x坐标
Graphics g=getGraphics();
g.drawLine(x1,y1,x2,y2); //以(x1,y1)为起点,(x2,y2)为终点画线
x1=x2; //更新绘线起点的x坐标
y1=y2; //更新绘线起点的y坐标
}
public void mouseMoved(MouseEvent?e){}
}

//app14_3.java 用鼠标拖动来绘画椭圆
import java.awt.*;
import java.awt.event.*;
public class app14_3 extends Frame implements MouseMotionListener, MouseListener
{
static app14_3 frm=new app14_3();
int px1,py1,px2,py2,status=0;
int rpx1,rpy1,rpx2,rpy2;
public static void main(String[] args)
{
frm.setTitle("鼠标拖动画椭圆");
frm.setSize(250,230);
frm.addMouseMotionListener(frm); //设置监听者
frm.addMouseListener(frm); //设置监听者
frm.setVisible(true);
}
public void mouseMoved(MouseEvent?e)
{
px1=e.getX();
py1=e.getY();
status=0;
}
public void mouseDragged(MouseEvent?e) //用鼠标拖动来画椭圆
{
Graphics g=getGraphics();
g.setColor(Color. yellow); //设置当前绘图颜色为黄色
g.setXORMode(Color.black); //设置以异或模式作图
if (status==1) g.drawOval (px1,py1,px2,py2); //判断是否为新画的椭圆
else {
px1=e.getX();
py1=e.getY();
status=1;
}
px2=Math.abs(e.getX()-px1); //计算长径
py2= Math.abs(e.getY()-py1); //计算宽径
g.drawOval (px1,py1,px2,py2); //画椭圆
rpx1=px1;rpy1=py1;rpx2=px2;rpy2=py2; //保存坐标位置
}
public void mouseReleased(MouseEvent e)
{
Graphics g=getGraphics();
g.setColor(Color.red);
g.drawOval (rpx1,rpy1,rpx2,rpy2);
}
public void mousePressed(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
}

//App15_1.java 小程序的应用
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class App15_1 extends Applet implements MouseListener
{
int x1,y1,x2,y2,width,height;
boolean flag=false;
public void init() //初始化方法
{
this.addMouseListener(this); //设置小程序本身为自己的监听者
}
public void mousePressed(MouseEvent?e)
{
flag=true;
x1= e.getX();
y1= e.getY();
}
public void mouseReleased(MouseEvent?e) //松开鼠标事件源的处理操作
{
x2= e.getX(); //取得拖动鼠标时的x坐标
y2= e.getY(); //取得拖动鼠标时的y坐标
repaint();
}
public void paint(Graphics g)
{
if(flag)
{
width=Math.abs(x2-x1);
height=Math.abs(y2-y1);
if (x1>x2 && y1>y2) //取得矩形框左上角的坐标(x1,y1)
{ x1=x2; y1=y2; }
else if(x1>x2 && y1<y2) x1=x2;
else if(x1<x2 && y1>y2) y1=y2;
g.drawRect(x1,y1,width,height); //画矩形
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
}

<App15_1.html>
<html>
<applet
code="App15_1.class"
height=150
width=300
alt="很抱歉,您的浏览器不支持Java applet。"
align="Middle"
vspace="25">
</applet>
</html>

//App15_2.java 小程序接收HTML文件传递进来的参数
import java.awt.*;
import java.applet.Applet;
public class App15_2 extends Applet //定义主类
{
private String v_name; //定义变量用于接收HTML文件传入的参数
private int v_age;
public void init() //初始化方法
{
v_name=getParameter("vname"); //接收HTML文件传入的参数
v_age=Integer.parseInt(getParameter("age")); //接收参数并将参数转换为整型
}
public void paint(Graphics g)
{
g.drawString("姓名:"+ v_name+" ;年龄:"+ v_age,10,20);
//System.out.println("计算机系");
}
}

<App15_2.html>
<html>
<applet code="App15_2.class" height=150 width=300>
<Param name=vname value="刘洋">
<Param name=age value=24>
</applet>
</html>

//App15_3.java 在小程序里显示图像
import java.awt.*;
import java.applet.Applet;
public class App15_3 extends Applet //定义主类
{
Image img;
public void init() //初始化操作,将图像"海岸.jpg"装入img中
{
img=getImage(getCodeBase(),"海岸.jpg");
}
public void paint(Graphics g)
{
g.drawString("海岸风景",50,15); //在小程序窗口显示文字
g.drawImage(img,30,30,200,200,this); //将img显示在窗口中
play(getDocumentBase(),"留恋.mid"); //播放音乐"留恋.mid"
}
}

<App15_3.html>
<html>
<applet code="App15_3.class"
width=300
height=250 >
</applet>
</html>

//App15_4.java 在小程序里播放音乐
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.applet.AudioClip;
public class App15_4 extends Applet implements ItemListener
{
AudioClip[] midi=new AudioClip[3]; //定义AudioClip接口类型的数组
AudioClip song; //目前选取的音乐
Choice coi=new Choice(); //创建下拉列表对象
Button bnt_loop=new Button("循环");
Button bnt_stop=new Button("停止");
public void init()
{
String num;
for(int i=0;i<midi.length;i++)
{
num=String.valueOf(i+1);
midi[i]=getAudioClip(getCodeBase(),num+".mid");//取得音乐来源
}
coi.add("爱你多年"); coi.add("夜来香"); coi.add("爱人");
add(coi);
add(bnt_loop); add(bnt_stop);
coi.addItemListener(this); //将小程序本身设置为coi的监听者
bnt_loop.addActionListener(new MyActLit()); //设置监听者
bnt_stop.addActionListener(new MyActLit());
song=midi[0]; //设置启动小程序时播放的音乐
song.play(); //播放音乐
}
public void itemStateChanged(ItemEvent e)
{
song.stop(); //停止正在播放的音乐
int i=coi.getSelectedIndex(); //在下拉列表中选择播放音乐的序号
song=midi[i]; //设置待播放的音乐
song.play(); //播放音乐
}
class MyActLit implements ActionListener //定义内部类
{
public void actionPerformed(ActionEvent e) //处理按钮事件的程序代码
{
Button bnt=(Button) e.getSource(); //取得被选中的按钮
if (bnt==bnt_loop) song.loop(); //若选择“循环”按钮,则循环播放
else song.stop(); //若选择“停止”按钮,则停止播放
}
}
}
相应的HTML文件如下:
<App15_4.html>
<html>
<applet code="App15_4.class"
width=300
height=100 >
</applet>
</html>

//Clock.java 利用动画技术制作时钟
import java.awt.*;
import java.util.*;
import java.applet.*;
import java.text.SimpleDateFormat;
public class Clock extends Applet implements Runnable
{
private Thread timer=null;
private int lastxh,lastyh,lastxm,lastym,lastxs,lastys; //时分秒针线的位置
private SimpleDateFormat sdf; //日期格式
public void init()
{
lastxs=lastys=lastxm=lastym=lastxh=lastyh=0;
setBackground(Color.white); //设置小程序窗口背景为白色
//下面的语句是设定文字日期的显示格式
sdf=new SimpleDateFormat("yyyy年MM月dd日 a hh时mm分ss秒 EEEEE");
}
public void paint(Graphics g) //显示数字和图形时钟
{
int xh,yh,xm,ym,xs,ys,s,m,h,xcenter,ycenter;
Calendar cal= Calendar.getInstance(); //生成一个日历类对象
Date sdate = new Date(); //获取当前日期和时间
String today = sdf.format(sdate); //转换成一串规定格式的日期和时间字符串
cal.setTime(sdate); //设置日历对象的内容(日期和时间)
s=cal.get(Calendar.SECOND); //获取时钟的秒数
m=cal.get(Calendar.MINUTE); //获取时钟的分钟数
h=cal.get(Calendar.HOUR); //获取时钟的小时数
xcenter=getWidth()/2; ycenter=80; //表盘时钟的原点
xs=(int)(Math.cos(s* Math.PI /30-Math.PI/2)*45+xcenter);
ys=(int)(Math.sin(s*Math.PI/30-Math.PI/2)*45+ycenter);
xm=(int)(Math.cos(m*Math.PI/30-Math.PI/2)*40+xcenter);
ym=(int)(Math.sin(m*Math.PI/30-Math.PI/2)*40+ycenter);
xh=(int)(Math.cos((h*30+m/2)*Math.PI/180-Math.PI/2)*30+xcenter);
yh=(int)(Math.sin((h*30+m/2)*Math.PI/180-Math.PI/2)*30+ycenter);
g.setFont(new Font("TimesRoman",Font.PLAIN,14));
g.setColor(Color.blue);
g.drawOval(xcenter-52,ycenter-52,104,104); //画表盘
g.setColor(Color.darkGray);
g.drawString("9",xcenter-45,ycenter+5);
g.drawString("3",xcenter+40,ycenter+3);
g.drawString("12",xcenter-7,ycenter-37);
g.drawString("6",xcenter-4,ycenter+45);
//时间变化时,需要重新画各个指针,即先消除原有指针,然后画新指针
g.setColor(getBackground()); //用背景色画线,可以消除原来画的线
if (xs!=lastxs||ys!=lastys) //秒针变化
{
g.fillOval(lastxs-5,lastys-5,10,10); //擦除秒针头上的小圆
g.drawLine(xcenter,ycenter,lastxs,lastys); //擦除秒针
}
if (xm!=lastxm||ym!=lastym) //分针变化
{
g.drawLine(xcenter,ycenter-1,lastxm,lastym);
g.drawLine(xcenter-1,ycenter,lastxm,lastym);
}
if (xh!=lastxh||yh!=lastyh) //时针变化
{
g.drawLine(xcenter,ycenter-1,lastxh,lastyh);
g.drawLine(xcenter-1,ycenter,lastxh,lastyh);
}
g.setColor(Color.darkGray);
g.drawString(today,30,180); //显示数字时钟
g.setColor(Color.red);
g.fillOval(xs-5,ys-5,10,10); //画秒针上的小圆
g.drawLine(xcenter,ycenter,xs,ys); //画秒针
g.setColor(Color.blue);
g.drawLine(xcenter,ycenter-1,xm,ym); //用两条线画分针
g.drawLine(xcenter-1,ycenter,xm,ym);
g.drawLine(xcenter,ycenter-1,xh,yh); //用两条线画时针
g.drawLine(xcenter-1,ycenter,xh,yh);
lastxs=xs; lastys=ys; //保存指针位置
lastxm=xm; lastym=ym;
lastxh=xh; lastyh=yh;
}
public void start() //启动线程
{
if(timer==null)
{
timer=new Thread(this); //生成Thread对象实体
timer.start(); //启动生成的线程
}
}
public void stop()
{
if(timer!=null)
{
timer.interrupt(); //中断线程
timer=null; //去掉Thread对象,让系统将这个垃圾对象收走
}
}
public void run() //每隔一秒钟,刷新一次画面
{
while (timer!=null)
{
try { Thread.sleep(1000); }
catch (InterruptedException e) { }
repaint(); //调用paint()方法重画时钟
}
}
}
相应的HTML文件如下:
<Clock.html>
<html>
<applet code="Clock.class"
width=350
height=200 >
</applet>
</html>

//App15_6.java 放映卡通片
import java.util.*;
import java.awt.*;
import java.applet.*;
public class App15_6 extends Applet implements Runnable
{
Thread thrpic=null;
Image[] frame=new Image[10];
int frame_i=0,delay_time;
public void init()
{
int i;
String fps;
for(i=0;i<frame.length;i++) //加载图像到数组中
frame[i]=getImage(getDocumentBase(),"image/picture"+i+".gif");
fps=getParameter("frame_per_second");
if(fps==null) fps="10";
delay_time=1000/Integer.parseInt(fps); //设置两张图处理相隔的时间
}
public void paint(Graphics g)
{
g.drawImage(frame[frame_i],0,0,this);
}
public void start()
{
if(thrpic==null)
{
thrpic=new Thread(this);
thrpic.start();
}
}
public void stop()
{
thrpic.interrupt();
thrpic=null;
}
public void run()
{
while(true)
{
try { Thread.sleep(delay_time); }
catch (InterruptedException e) { }
repaint();
frame_i=(frame_i+1)%frame.length;
}
}
}

//app16_1.java 利用URL获取网上文件的内容
import java.net.*;
import java.io.*;
public class app16_1
{
public static void main(String[] args)
{
String urlname = "http://www.edu.cn/index.html";
if (args.length>0) urlname=args[0];
new app16_1().display(urlname);
}
public void display(String urlname)
{
try
{
URL url=new URL(urlname); //创建URL类对象url
InputStreamReader in=new InputStreamReader(url.openStream());
BufferedReader br=new BufferedReader(in);
String aLine;
while((aLine=br.readLine())!=null) //从流中读取一行显示
System.out.println(aLine);
}
catch(MalformedURLException murle)
{ System.out.println(murle); }
catch(IOException ioe)
{ System.out.println(ioe); }
}
}

//app16_2.java 利用InetAddress编程
import java.net.*;
public class app16_2
{
InetAddress myIPaddress=null;
InetAddress myServer=null;
public static void main(String[] args)
{
app16_2 Search=new app16_2();
System.out.println("您主机的IP地址为:"+ Search.MyIP());
System.out.println("服务器的IP地址为:"+ Search.ServerIP());
}
public InetAddress MyIP() //获取本地主机IP地址的方法
{
try //获取本机的IP地址
{ myIPaddress=InetAddress.getLocalHost(); }
catch(UnknownHostException e) { }
return (myIPaddress);
}
public InetAddress ServerIP() //获取本机所联服务器IP地址的方法
{
try //获取服务器的IP地址
{ myServer=InetAddress.getByName("www.tom.com"); }
catch(UnknownHostException e) { }
return (myServer);
}
}

服务器端的程序代码如下:
// MyServer.java Socket通信的服务器端程序
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class MyServer implements Runnable
{
ServerSocket server=null;
Socket clientSocket; //负责当前线程中C/S通信中的Socket对象
boolean flag=true; //标记是否结束
Thread ConnenThread; //向客户端发送信息的线程
BufferedReader sin; //输入流对象
DataOutputStream sout; //输出流对象
public static void main(String[] args)
{
MyServer MS=new MyServer();
MS.ServerStart();
}
public void ServerStart()
{
try
{
server = new ServerSocket(8080); //建立监听服务
System.out.println("端口号:"+server.getLocalPort());
while(flag)
{
clientSocket=server.accept();
System.out.println("连接已经建立完毕!");
InputStream is=clientSocket.getInputStream();
sin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
sout=new DataOutputStream(os);
ConnenThread=new Thread(this);
ConnenThread.start(); //启动线程,向客户端发送信息
String aline;
while((aline=sin.readLine())!=null) //从客户端读入信息
{
System.out.println(aline);
if(aline.equals("bye"))
{
flag=false;
ConnenThread.interrupt(); //线程中断
break;
}
}
sout.close(); //关闭流
os.close();
sin.close();
is.close();
clientSocket.close(); //关闭Socket连接
System.exit(0); //程序运行结束
}
}
catch(Exception e)
{ System.out.println(e); }
}
public void run()
{
while(true)
{
try
{
int ch;
while((ch=System.in.read())!=-1)
{ //从键盘接收字符并向客户端发送
sout.write((byte)ch);
if(ch=='\n')
sout.flush(); //将缓冲区内容向客户端输出
}
}
catch(Exception e)
{ System.out.println(e); }
}
}
public void finalize() //析构方法
{
try
{ server.close(); } //停止ServerSocket服务
catch(IOException e)
{ System.out.println(e); }
}
}

客户端程序代码如下:
// MyClient.java Socket通信的客户端程序
import java.net.*;
import java.io.*;
public class MyClient implements Runnable
{
Socket clientSocket;
boolean flag=true; //标记是否结束
Thread ConnenThread; //用于向服务器端发送信息
BufferedReader cin;
DataOutputStream cout;
public static void main(String[] args)
{ new MyClient().ClientStart(); }
public void ClientStart()
{
try
{ //连接服务器端,这里使用本机
clientSocket=new Socket("localhost",8080);
System.out.println("已建立连接!");
while(flag)
{ //获取流对象
InputStream is=clientSocket.getInputStream();
cin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
cout=new DataOutputStream(os);
ConnenThread=new Thread(this);
ConnenThread.start(); //启动线程,向服务器端发送信息
String aline;
while((aline=cin.readLine())!=null)
{ //接收服务器端的数据
System.out.println(aline);
if(aline.equals("bye"))
{
flag=false;
ConnenThread.interrupt();
break;
}
}
cout.close();
os.close();
cin.close();
is.close();
clientSocket.close(); //关闭Socket连接
System.exit(0);
}
}
catch(Exception e)
{ System.out.println(e); }
}
public void run()
{
while(true)
{
try
{ //从键盘接收字符并向服务器端发送
int ch;
while((ch=System.in.read())!=-1)
{
cout.write((byte)ch);
if(ch=='\n')
cout.flush(); //将缓冲区内容向输出流发送
}
}
catch(Exception e)
{ System.out.println(e); }
}
}
}

客户端程序代码:
// UDPClient.java UDP通信的客户端程序
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main(String[] args)
{
UDPClient frm=new UDPClient();
}
CliThread ct; //声明客户类线程对象ct
public UDPClient() //构造方法
{
ct=new CliThread(); //创建线程
ct.start(); //启动线程
}
}
class CliThread extends Thread //客户端线程类,负责发送信息
{
public CliThread() {} //构造方法
public void run()
{
String str1;
String servername="CGJComputer"; //服务器端计算机名
System.out.println("请发送信息给服务器《"+servername +"》");
try
{
DatagramSocket skt=new DatagramSocket(); //建立UDP socket对象
DatagramPacket pkt; //建立DatagramPacket对象pkt
while(true)
{
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入信息:");
str1=buf.readLine(); //从键盘上读取数据
byte[] outbuf=new byte[str1.length()];
outbuf=str1.getBytes();
//下面是取得服务器端地址
InetAddress address=InetAddress.getByName(servername);
pkt=new DatagramPacket(outbuf,outbuf.length,address,8000);//数据打包
skt.send(pkt); //发送UDP数据报分组
}
}catch (IOException e) {}
}
}

服务器端程序代码:
// UDPServer.java UDP通信的服务器端程序
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main(String[] args)
{
UDPServer frm=new UDPServer();
}
String strbuf= " ";
SerThread st; //声明服务器类线程对象st
public UDPServer()
{
st=new SerThread(); //创建线程
st.start(); //启动线程
}
}
class SerThread extends Thread //服务器类线程,负责接收信息
{
public SerThread() {} //构造方法
public void run()
{
String str1;
try
{ //使用8000端口,建立UDP Socket对象
DatagramSocket skt=new DatagramSocket(8000);
System.out.print("服务器名:");
//显示服务器计算机的名称
System.out.println(InetAddress.getLocalHost().getHostName());
while(true)
{
byte[] inbuf=new byte[256];
//下面是取得服务器端地址
DatagramPacket pkt;
//创建并设置接收pkt对象的接收信息
pkt=new DatagramPacket(inbuf,inbuf.length);
skt.receive(pkt); //接收数据报分组
//提取接收到的分组中的数据并转成字符串
str1=new String(pkt.getData());
str1=str1.trim(); //去掉字符串中的首尾空格
if(str1.length()>0)
{
int pot=pkt.getPort(); //获取远程端口号
System.out.println("远程端口:"+pot);
System.out.println("服务器已接收到信息:"+str1);
}
}
}catch (IOException e) { return; }
}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2011-12-25 21:56  zhiyinjixu  阅读(718)  评论(0)    收藏  举报