第二章习题答案
1.什么是对象、类,它们之间的联系?
答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象! 3) 两者的关系:对象是类的具体实例.。
4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。 区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;
6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用? 答:
类成员的访问控制符有 public,private,protecte及无修饰符.
public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).
Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。 proteced(保护的)用该关键字修饰的成分是受保护的,只可以被同一类及其子类的实例对象访问。
无修饰符(默认的):public,private,protected这个三个限定符不是必须写的。如果不写,则表明是“friendly”,相应的成分可以被所在保重的各类访问。
8简述构造方法的特点? 答:
构造方法主要有以下特点:
(1) 构造方法的方法名与类名相同;
(2) 构造方法没有返回类型(修饰符void也不能有); (3) 构造方法通常被声明为公有的(public);
(4) 构造方法可以有任意多个参数;
(5) 构造方法的主要作用是完成对象的初始化工作; (6) 构造方法不能在程序中显式的调用;
(7) 在生成一个对象时,系统会自动调用该类的构造方法为新生成的对象初始化。
9如果在类声明中声明了构造方法,系统是否还提供默认的构造方法? 答:
用户在进行类声明时,如果没有声明任何构造方法,系统会赋给此类一个默认(无参)的构造方法。但是,只要用户声明了构造方法,即使没有声明无参的构造方法,系统也不会再赋默认的构造方法。
11:声明并测试一个复数类,其方法包括toString()及复数的加、减、乘运算。
答:public class Complex {
private float a; private float b;
public String toString() {if(a!=0)
return(a+\"i\"+\"+\"+b); else return(\"\"+b); }
public Complex(float a,float b) {
this.a=a; this.b=b; }
public void Add(Complex p) {
this.a+=p.a; this.b+=p.b; }
public void Decrease(Complex p) {
this.a-=p.a; this.b-=p.b; }
public void Multiply(Complex p) {
this.a=this.a*p.a; this.b=this.b*p.b;
} }
public class ComplexTexter {
public static void main(String args[]) {
Complex a=new Complex(2,4); Complex b=new Complex(5,8);
a.Add(b);System.out.println(a.toString()+\"\\n\");
a.Decrease(b);System.out.println(a.toString()+\"\\n\"); a.Multiply(b);System.out.println(a.toString()+\"\\n\"); } }
、
12:什么是UML?它由哪几部分组成? 答:
UML是图形化()即可视化的建模语言,成为面向对象建模的标准语言。 它由四部分组成:(1)视图(2)图(3)模型元素(4)通用机制 13. 常用的类与类之间的关系有哪几种。 答:有关联、依赖、流、泛化、实现、使用。
Java语言程序设计(郑莉) 第三章课后习题答案
1.设N为自然数: n!=1*2*3*….*n
称为n的阶乘,并且规定0!=1.试编程计算2!,4!,6!he 10!.并将结果输出到屏幕上。 答:
public class Mul {
public static void main(String args[])
{
int i,n; float s;
for(n=0;n<=10;n=n+2) {
if(n==0)
System.out.println(\"0!=1\\n\"); else {s=1;
for(i=1;i<=n;i++) s=s*i;
System.out.println(n+\"!=\"+s+\"\\n\"); } } } }
2.编写程序,接收用户从键键盘上输入的三个整数x,y,z..从中选出最大和最小者,并编程实现。
答:public class Math{
public static void main(String args[]){ int[] IntArg = new int[args.length]; for(int i=0;i } int max,min; max=IntArg[0]>IntArg[1]?IntArg[0]:IntArg[1]; max=max>IntArg[2]?max:IntArg[2]; min=IntArg[0] public class Su{ public static void main(String args[]){ int n,i,k=0,y; for(n=2;n<=100;n++){ y=1; for(i=2;i System.out.print(\"\\n\"); } } } } 4.使用java.lang.Math类,生成100个0---99之间的随机整数,找出他们之中的最大值和最小值,并统计大于50的整数个数。 public class Random{ public static void main(String[] args) { int MinNum,MaxNum,n=0; int[] array=new int[100]; array[0]=(int)(Math.random()*100); MinNum=array[0]; MaxNum=array[0]; System.out.println(\"数列为:\"); System.out.print(array[0]+\" \"); for(int i=0;i<100;i++) { array[i]=(int)(Math.random()*100); if(array[i]>50) n++; if(array[i]>=MaxNum) MaxNum=array[i]; if(array[i]<=MinNum) MinNum=array[i]; System.out.print(array[i]+\" \"); } System.out.println(); System.out.println(\"MinNum=\"+MinNum); System.out.println(\"MaxNum=\"+MaxNum); System.out.println(\"大于50的整数个数有:\"+n); } } 7.什么是异常?解释抛出、捕获的含义。 答:异常又称为例外,是特殊的运行错误对象,在程序中可以强制编译器来处理程序运行中的发生的并非由程序本身所造成的错误; 抛出异常:把生成异常对象并提交的过程称为抛出异常; 抛出异常是java中一个程序处理动作,检查异常时要么在方法中声明一个异常抛出,用try-catch语句捕获异常,并进行处理。 8.简述Java的异常处理机制。 答:java中声明了很多异常类,每个异常类都代表了一种运行错误,类中包含了该运行错误的信息和处理错误的方法等内容。每当java程序运行过程中发生一个可识别的运行错误时,即该错误有一个异常类与之相对应时,系统都会产生一个相应的该异常类的对象,即产生一个异常。一旦一个异常对象产生了,系统中就一定有相应的机制来处理它,确保不会产生死机、死循环或其他对操作系统的损害,从而保证了整个程序运行的安全性。 9.系统定义的异常与用户自定义的异常有何不同?如何使用这两类异常? 答:系统定义的特定情况出现的问题,而此时用来对可能遇到的问题进行处理。用户定义的是自己觉得可能会出现问题时,需要处理的。这样避免程序中断或是出现未知错误。 系统异常有两种一种是运行时异常,一种是普通异常,普通异常要求用户捕获或者抛出的,不补货或者抛出就会编译不通过。运行时异常编译可以通过,但是运行时才显露出来。 10.用户如何自定义异常?编程实现一个用户自定义异常。 (1)定义mytest import java.io.*; public class mytest{ private static int quotient(int number,int denominator)throws DivideByZeroException{ if(denominator==0) throw new DivideByZeroException(); return(number/denominator); } public static void main(String args[]){ int number1=0,number2=0, result=0; try{ System.out.println(\"输入第一个数字:\"); number1=Integer.valueOf(Keyboard.getString()).intValue(); System.out.println(\"输入第二个数字:\"); number2=Integer.valueOf(Keyboard.getString()).intValue(); result=quotient(number1,number2); } catch(NumberFormatException e){ System.out.println(e.toString()); System.exit(-1); } System.out.println(number1+\"/\"+number2+\"=\"+result); } } (2)定义DivideByZeroException public class DivideByZeroException extends ArithmeticException{ public DivideByZeroException(){ super(\"除数不能为0!\"); } } (3)定义Keyboard import java.io.*; public class Keyboard{ static BufferedReader inputStream=new BufferedReader(new InputStreamReader(System.in)); public static int getInteger(){ try{ return (Integer.valueOf(inputStream.readLine().trim()).intValue()); }catch(Exception e){ e.printStackTrace(); return 0; } } public static String getString(){ try{ return(inputStream.readLine()); }catch(IOException e){return \"0\";} } } Java语言程序设计 第四章课后习题答案 1.子类将继承父类所有的属性和方法吗?为什么? 答:不,子类不能直接访问从父类中继承的私有属性及方法,但可以对公有及保护方法进行访问。 2.方法的覆盖与方法的重载有何不同? 答:覆盖是运用在子类中实现与父类相同的功能,但采用不同的算法或公式;在名字相同的方法中,要做比父类更多的事情;在子类中需要取消从父类继承的方法。 8.什么是抽象类?抽象类中是否一定要包括抽象方法? 答:抽象类是一个不完全的类,不能使用new方法进行实例化。 抽象类可以包含抽象方法,也可以不包含抽象方法,但有抽象方法的必须是抽象类。 9.this和super分别有哪些特殊含义?都有哪些种用法? 答:this 表示当前类;super 表示调用父类。 在定义类的时候用到,this是当前对象的引用,super是当前对象的父类对象的引用,一般的都是把super用在构造函数中。 10.完成下面父类及子类的声明: (1) 声明Student类属性包括学号、姓名、英语成绩、数学成绩、计算机成绩和总成绩。方法包括构造方法、get方法、 set方法、toString方法、equals方法、compare方法(比较两个学生的总成绩,结果分为大于、小于、等于),sum方法(计算总成绩)和testScore方法(计算评测成绩)。 注:评测成绩可以取三门课成绩的平均分,另外任何一门课的成绩的改变都需要对总成绩进行重新计算,因此,在每一个set方法中应调用sum方法计算总成绩。 public class Student{ String id; String name; float scoreOfenglish; float scoreOfmath; float scoreOfcomputer; float scoreOfsum; //构造方法 public Student(){ } public Student(String aid,String aname,float ascoreOfenglish,float ascoreOfmath,float ascoreOfcomputer){ this.id=aid; this.name=aname; this.scoreOfenglish=ascoreOfenglish; this.scoreOfmath=ascoreOfmath; this.scoreOfcomputer=ascoreOfcomputer; //this.scoreOfsum=ascoreOfenglish+ascoreOfmath+ascoreOfcomputer; this.scoreOfsum=sum(); } //sum方法 public float sum(){ return(this.scoreOfenglish+this.scoreOfmath+this.scoreOfcomputer); } //testScore测评成绩/平均分 public float testScore(){ return(this.scoreOfsum/3); } //6个get方法 public String getid(){ return(id); } public String getname(){ return(name); } public float getscoreOfenglish(){ return(scoreOfenglish); } public float getscoreOfmath(){ return(scoreOfmath); } public float getscoreOfcomputer(){ return(scoreOfcomputer); } public float getscoreOfsum(){ return(scoreOfsum); } //5个set方法 public void setid(String newid){ this.id=newid; } public void setname(String newname){ this.name=newname; } public void setscoreOfenglish(float newscoreOfenglish){ this.scoreOfenglish=newscoreOfenglish; this.scoreOfsum=sum(); } public void setscoreOfmath(float newscoreOfmath){ this.scoreOfmath=newscoreOfmath; this.scoreOfsum=sum(); } public void setscoreOfcomputer(float newscoreOfcomputer){ this.scoreOfcomputer=newscoreOfcomputer; this.scoreOfsum=sum(); } //toString方法 public String toString(){ return(\"学号:\"+this.id+\"\\n姓名:\"+name+\"\\n英语:\"+this.scoreOfenglish+\"\\n数学:\"+this.scoreOfmath+\"\\n计算机:\"+this.scoreOfcomputer+\"\\n总分:\"+this.scoreOfsum); } //compare方法/比较2学生总分 public void compare(Student x){ if(this.getscoreOfsum()>x.getscoreOfsum())System.out.println(this.getname()+\"总分大于\"+x.getname()); if(this.getscoreOfsum() //equals方法/比较2学生学号是否相等(还没完善) /* * public boolean equals(Object x){ if(this.getClass()!=x.getClass())return false; Student b=(Student)x; if(this.id==b.getid())return true; } */ } (2)声明StudentXW(学习委员)类为Student类的子类。 在StudentXW类中增加责任属性,并重写testScore方法(评测成绩=三门课平均分+3) public class StudentXW extends Student{ String responsibility; //构造方法 public StudentXW(){ super(); //responsibility=\" \"; } public StudentXW(String aid,String aname,float ascoreOfenglish,float ascoreOfmath,float ascoreOfcomputer,String aresponsibility){ super(aid,aname,ascoreOfenglish,ascoreOfmath,ascoreOfcomputer); responsibility=aresponsibility; } //testScore测评成绩/平均分 public float testScore(){ return(this.scoreOfsum/3+3); } //toString方法 public String toString(){ return(\"学号:\"+this.id+\"\\n姓名:\"+name+\"\\n英语:\"+this.scoreOfenglish+\"\\n数学:\"+this.scoreOfmath+\"\\n计算机:\"+this.scoreOfcomputer+\"\\n总分:\"+this.scoreOfsum+\"\\n职位:\"+this.responsibility); } } (3)声明StudentBZ类为Student类的子类 在StudentBZ类中增加责任属性,并重写testScore方法(评测成绩=三门课平均分+5) public class StudentBZ extends Student{ String responsibility; //构造方法 public StudentBZ(){ super(); //responsibility=\"\"; } public StudentBZ(String aid,String aname,float ascoreOfenglish,float ascoreOfmath,float ascoreOfcomputer,String aresponsibility){ super(aid,aname,ascoreOfenglish,ascoreOfmath,ascoreOfcomputer); responsibility=aresponsibility; } //testScore测评成绩/平均分 public float testScore(){ return(this.scoreOfsum/3+5); } //toString方法 public String toString(){ return(\"学号:\"+this.id+\"\\n姓名:\"+name+\"\\n英语:\"+this.scoreOfenglish+\"\\n数学:\"+this.scoreOfmath+\"\\n计算机:\"+this.scoreOfcomputer+\"\\n总分:\"+this.scoreOfsum+\"\\n职位:\"+this.responsibility); } } 4)声明测试类,生成若干个Student类、StudentXW类及StudentBZ类对象,并分别计算它们的评测成绩(建议采用:写一个测试函数,该函数以父类student数组作为参数) 。 import java.text.*; public class test4_10{ public static void main(String args[]){ Student su=new Student(\"001\苏轼\ Student du=new Student(\"002\杜甫\ Student bai=new Student(\"003\白居易\ Student liu=new Student(\"004\柳宗元\ StudentXW ou=new StudentXW(\"005\欧阳修\数学代表\"); StudentXW wang=new StudentXW(\"006\王安石\英语代表\"); StudentBZ li=new StudentBZ(\"007\李白\班长\"); System.out.print(li); System.out.println(\"\\n评测成绩:\"+new DecimalFormat(\"0.00\").format(li.testScore())); System.out.println(); System.out.print(wang); System.out.println(\"\\n评测DecimalFormat(\"0.00\").format(wang.testScore())); System.out.println(); System.out.print(ou); System.out.println(\"\\n评测 DecimalFormat(\"0.00\").format(ou.testScore())); System.out.println(); System.out.print(su); System.out.println(\"\\n评测DecimalFormat(\"0.00\").format(su.testScore())); System.out.println(); System.out.print(du); System.out.println(\"\\n评测DecimalFormat(\"0.00\").format(du.testScore())); System.out.println(); System.out.print(bai); System.out.println(\"\\n评测DecimalFormat(\"0.00\").format(bai.testScore())); System.out.println(); System.out.print(liu); System.out.println(\"\\n评测DecimalFormat(\"0.00\").format(liu.testScore())); } } 运行test4_10的结果如下: 成 绩 成绩成绩成绩成绩成绩: \"+new :\"+new :\"+new :\"+new :\"+new :\"+new (很好玩吧,李白,我让你挂科。) 11.包有什么作用?如何创建包和引用包中的类? 答:包是一种松散的类的组合,一般不要求处于同一包中的类型有明确的相互关系,但由于同一包中的类在默认情况下可以相互访问,所以为了方便编程和管理,通常把需要在一起工作的类放在一个包里。利用包来管理类,可实现类的共享与复用。 在操作系统中,目录用来组织文件,设置权限。只要在要用到包中类的时候,在该引用类的第一行加上:package (包的全路径)即可。 Java语言程序设计 第五章课后习题答案 1.什么是接口?接口起什么作用?接口与抽象类有何区别? 答:Java中的接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能)。 作用:接口是面向对象的一个重要机制,使用接口可以实现多态继承;接口中的所有方法都是抽象的,这些抽象方法由实现这一接口的不同类型来具体;接口还可以用来实现不同类之间的常量共享。 与抽象类不同的是:接口允许在看起来不相干的类之间定义共同行为。 3.在什么情况下,可以对父类对象的引用进行强制类型转换,使其转化成子类对象的引用? 答:一个对象被塑型为父类或接口后,可以再一次被塑型回到它原来所属的类,即转化成原类对象的引用。 4.声明一个接口,此接口至少具有一个方法;在一个方法中声明内部类实现此接口,并返回此接口的引用。 //A类接口 public interface A{ void fuck(); } //B类 public class B{ public A fuck(){ return new A(){ public void fuck(){ System.out.println(\"B类声明实现A接口类并返回接口的应用——Fuck you!\"); } };/*注意这里有分号“;”*/ } } //test5_4 public class test5_4 { public static void main(String[] args){ new B().fuck().fuck(); } } 运行结果: 7.什么是多态?如何实现多态? 答:多态性是指不同类型的对象可以响应相同的消息。利用向上塑性技术,一个父类的应引用变量可以指向不同的子类对象;而利用动态绑定技术,可以再运行时根据父类引用变量所指对象的世纪类型执行相应的子类方法,从而实现多态性。 Java语言程序设计 第六章课后习题答案 3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。 // memory存储类 import java.io.*; import java.util.Random; public class memory { private String name; private int count; private int Max; private int Min; public memory(String n,int c,int min,int max){ this.name=n; this.count=c; this.Min=min; this.Max=max; } public void startmemory(){ try{ FileWriter out=new FileWriter(name); int limit=Max-Min; Random random = new Random(); for (int i=1;i<=count;i++){ int number=Min+random.nextInt(limit); System.out.print(number); System.out.print(\" \"); out.write(number+\" \"); } out.close(); }catch(IOException iox){ System.out.println(\"方法startmemory()有问题\"); } } } //test6_3 import java.io.*; import java.util.Scanner; public class test6_3 { public static void main(String[] args) throws IOException{ //BufferedReader String fileName; int count,min,max; Scanner in = new Scanner(System.in); System.out.println(\"输入要存储的文件名\"); fileName=in.next(); System.out.println(\"输入随机数个数\"); count=in.nextInt(); System.out.println(\"输入随机数最小值\"); } } } min=in.nextInt(); System.out.println(\"输入随机数最大值\"); max=in.nextInt(); memory M=new memory(fileName,count,min,max); M.startmemory(); 运行结果: naruto文件存储二进制数: 6.用记事本程序创建一篇包含几十个英语单词的小文章,要求从屏幕输出每一个单词。 //test6_6 import java.io.*; public class test6_6 { public static void main(String[] args)throws IOException { FileReader fr=new FileReader(\"naruto.txt\"); int s; while((s=fr.read())!=-1){ if(s>='a'&& s<='z'|| s>='A' && s<='Z') System.out.print((char)s); else System.out.print(\"\\n\"); } fr.close(); } } 运行结果: 8.创建一个学生类(包括姓名、年龄、班级、密码),创建若干该类的对象并保存在文件中(密码不保存),从文件读取对象后显示在屏幕上。 //Student类 import java.io.Serializable; class Student implements Serializable{ String name; int age; int grade; transient String secret; public Student(String name,int age,int grade,String secret){ this.name=name; this.age=age; this.grade=grade; this.secret=secret; } } //test6_8 import java.io.*; public class tset6_8 { public static void main(String[] args) throws IOException,ClassNotFoundException{ Student student[]={ new Student(\"苍井空\",19,101,\"changjingkong\"), new Student(\"吉沢明\",19,103,\"jizeming\"), new Student(\"武藤兰\",20,104,\"wutenglan\"), new Student(\"我爱女优\",21,105,\"woainvyou\")}; //创建输出 ObjectOutputStream oos=new ObjectOutputStream( new FileOutputStream(\"naruto.dat\")); for(int i=0;i 1.数组的声明与数组元素的创建有什么关系? 答:声明数组仅仅是代表试图创建数组,不分配任何存储空间,声明是为创建做“铺垫”。 2.Vector类的对象与数组有什么关系?什么时候适合使用数组,什么时候适合使用Vector? 答:vector是一个能够存放任意对象类型的动态数组,容量能自动扩充,而数组存储固定且类型相同的对象;对于存储固定类型相同的对象使用数组,对于存储不同类型或者动态调整数组大小的情况使用Vector。 3.与顺序查找相比,二分查找有什么优势?使用二分查找的条件? 答:对于大数据量中进行查找时二分查找比顺序查找效率高得多;条件是已排序的数组。 4.试举出三种常见的排序算法,并简单说明其排序思路。 答:①选择排序:基本思想是站在未排序列中选一个最小元素,作为已排序子序列,然后再重复地从未排序子序列中选取一个最小元素,把它加到已经排序的序列中,作为已排序子序列的最后一个元素,直到把未排序列中的元素处理完为止。 ②插入排序:是将待排序的数据按一定的规则逐一插入到已排序序列中的合适位置处,直到将全部数据都插入为止。 ③二分查找:将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。 5.声明一个类People,成员变量有姓名、出生日期、性别、身高、体重等;生成10个People类对象,并放在一个以为数组中,编写方法按身高进行排序。 //People类 public class People{ private String name; private String birthdaydate; private String sex; private double height; private double weight; public People(){//默认构造函数 } public People(People p){ this.name=p.name; this.birthdaydate=p.birthdaydate; this.sex=p.sex; this.height=p.height; this.weight=p.weight; } public People(String name,String birthdaydate,String sex,double height,double weight){ this.name=name; this.birthdaydate=birthdaydate; this.sex=sex; this.height=height; this.weight=weight; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirthdaydate() { return birthdaydate; } public void setBirthdaydate(String birthdaydate) { this.birthdaydate = birthdaydate; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public String toString(){ return \"姓名:\"+name+\"\\n出生年月:\"+birthdaydate+\"\\n性别:\"+sex+\"\\n身高:\"+height+\"\\n体重:\"+weight; } } //test7_5类 public class test7_5 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub People[] people={ new People(\"林楚金\",\"1989年8月13日\",\"男\",182,63.5), new People(\"诸葛亮\",\"181年7月23日\",\"男\",184,76.6), new People(\"迈克杰克逊\",\"1958年8月29日\",\"男\",180,60), new People(\"乔丹\",\"1963年2月17日\",\"男\",198,98.1), new People(\"拿破仑\",\"1769年8月15日\",\"男\",159.5,63), new People(\"苍井空\",\"1983年11月11日\",\"女\",155,45),}; People temp=new People(); for(int i=0;i 6.声明一个类,此类使用私有的ArrayList来存储对象。使用一个Class类的引用得到第一个对象的类型之后,只允许用户插入这种类型的对象。 // Fuck类 import java.util.ArrayList; public class Fuck { private ArrayList man=new ArrayList(); private Class classType=null; public void add(Object f){ if(man.size()==0){ classType=f.getClass(); } if(classType.equals(f.getClass())){ man.add(f); System.out.println(\"插入成功.\"); } else{ System.out.println(\"只允许插入\"+getClassType()+\"类的对象.\"); } } public ArrayList getMan() { return man; } public Class getClassType() { return classType; } public Fuck(){} } //test7_6 public class test7_6 { public static void main(String[] args) { Fuck fuckman=new Fuck(); String s=new String(\"林楚金\"); fuckman.add(s); fuckman.add(10);//测试插入插入整数 fuckman.add('f');//测试插入插入字符 fuckman.add(\"希特勒\"); System.out.println(fuckman.getMan()); } } 运行结果: Java语言程序设计 第八章课后习题答案 1.进程和线程有何区别,Java是如何实现多线程的。 答:区别:一个程序至少有一个进程,一个进程至少有一个线程;线程的划分尺度小于进程;进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。 Java程序一般是 继承Thread 类 或者实现 Runnable接口,从而实现多线程。 2.简述线程的生命周期,重点注意线程阻塞的几种情况,以及如何重回就绪状态。 答:线程的声明周期:新建-就绪-(阻塞)-运行--死亡 线程阻塞的情况:休眠、进入对象wait池等待、进入对象lock池等待; 休眠时间到回到就绪状态;在wait池中获得notify()进入lock池,然后获得锁棋标进入就绪状态。 3.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。 (注:两个类,相同一个测试类) //Runnable接口实现的线程runable类 public class runnable implements Runnable { private String city; public runnable() {} public runnable(String city) { this.city = city; } public void run() { for (int i = 0; i < 10; i++) { System.out.println(city); try { //休眠1000毫秒。 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } // Thread类实现的线程thread类 public class runnable extends Thread { private String city; public runnable() {} public runnable(String city) { this.city = city; } public void run() { for (int i = 0; i < 10; i++) { System.out.println(city); try { //休眠1000毫秒。 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } //test8_3 public class test8_3 { public static void main(String[] args) { // 将创建一个线程对象,这个对象接受一个实现了Runnable接口。实际上这里也就是使用run()方法 runnable r1=new runnable(\"广州\"); runnable r2=new runnable(\"乌鲁木齐\"); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); // 启动线程 t1.start(); t2.start(); } } 运行结果分别为: 5.实现一个数据单元,包括学号和姓名两部分。编写两个线程,一个线程往数据单元中写,另一个线程往外读。要求没写一次就往外读一次。 //Data类 import java.util.Scanner; public class Data{ String studentId; String name; } boolean available = false;// 判断是读是写 Scanner in = new Scanner(System.in);// 定义一个输入对象 public synchronized void read() { if(available) try { wait(); } catch(Exception e) { } System.out.printf(\"请输入学号:\"); try { studentId=in.next(); } catch(Exception e) { System.out.println(\"输入学号出错!\"); } System.out.printf(\"请输入姓名:\"); try { name=in.next(); } catch(Exception e) { System.out.println(\"输入姓名出错!\"); } System.out.println(); available=true; notify(); } public synchronized void write() { if(!available) try { wait(); } catch(Exception e) { } System.out.println(\"输出学生学号:\"+studentId+\" 姓名:\"+name+\"\\n\"); available=false; notify(); } //Read类 public class Read extends Thread{ Data d1 = null; public Read(Data d){ this.d1=d; } } public void run(){ while(true) { d1.read(); } } //Write类 class Write extends Thread{ Data d2=null; public Write(Data d) { this.d2=d; } public void run() { while(true) { d2.write(); } } } //test8_5类 public class test8_5 { public static void main(String[] args){ Data data=new Data(); new Read(data).start(); new Write(data).start(); } } 运行结果: Java语言程序设计 第九章课后习题答案 3.编写一个Applet,该程序请求用户输入圆的半径,然后显示该圆的直径、周长和面积。 //test9_3 import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class test9_3 extends JApplet { //声明5个标签 private JLabel jLabel1; private JLabel jLabel2; private JLabel jLabel3; private JLabel jLabel4; private JLabel jLabel5; //1个单行文本 private JTextField textOfRadius; //2个按钮 private JButton jButton1; private JButton jButton2; //初始化 public void init() { try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { ex.printStackTrace(); } } private void initComponents() { //声明8个组件 jLabel1 = new JLabel(\"输入圆的半径:\", SwingConstants.CENTER); jLabel2 = new JLabel(\"圆的周长:\", SwingConstants.CENTER); jLabel3 = new JLabel(\"\", SwingConstants.CENTER); jLabel4 = new JLabel(\"圆的面积:\", SwingConstants.CENTER); jLabel5 = new JLabel(\"\", SwingConstants.CENTER); textOfRadius = new JTextField(\"半径\"); jButton1 = new JButton(\"计算\"); jButton2 = new JButton(\"退出\"); //按钮添加监听器 jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jButton1ActionPerformed(evt); } }); //按钮添加监听器 jButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { jButton2ActionPerformed(evt); } }); //声明定义内容面板,并且设置其布局格式为:4行2列格子 Container c = getContentPane(); c.setLayout(new GridLayout(4, 2)); //将8个组件加入到内容面板 c.add(jLabel1); c.add(textOfRadius); c.add(jLabel2); c.add(jLabel3); c.add(jLabel4); c.add(jLabel5); c.add(jButton1); c.add(jButton2); } // 求周长方法 private String Round(double a) { double perimeter = a * 2 * 3.14; String s = new String(String.valueOf(perimeter)); return s; } // 求面积方法 private String Area(double a) { double area = a * a * 3.14; String s = new String(String.valueOf(area)); return s; } //点击“计算”按钮jButton1触发的方法 private void jButton1ActionPerformed(ActionEvent evt) { //捕获单文本输入非数字的异常 try { String s = textOfRadius.getText();//获得单文本字符 double a = Double.valueOf(s).floatValue();//字符转化为双精度 jLabel3.setText(Round(a));//标签内容为周长 jLabel5.setText(Area(a));//标签内容为面积 } catch (NumberFormatException r) { //单文本为非数字弹出提示“输入错误”框 JOptionPane.showMessageDialog(this, \"请输入数字类型\", \"输入错误\",JOptionPane.WARNING_MESSAGE); textOfRadius.setText(\"\"); } } //点击“退出”按钮jButton2触发的方法 public void jButton2ActionPerformed(ActionEvent evt) { System.exit(0); } } 运行结果: 编译text9_3.java产生字节码文件test9_3.class,接下来需要编写一个 HTML文件text9_3.html来嵌入text9_3.class,代码如下: 将test9_3.html文件和test9_3.class文件放在同一个目录下,在浏览器中打开这个test9_3.html文件,实现的效果如下: 6.编写一个“猜数”程序:该程序随机在1到100的范围内选择一个供用户猜测的整数,然后改程序显示提示信息,要求用户输入一个1到100之间的整数,根据输入偏大、偏小、正确,程序将显示不同的图标。 //GuessNumber类 import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingConstants; public class GuessNumber extends JFrame implements ActionListener { int numberOfRandom;// 游戏程序随机数 int numberOfUser;// 玩家输入整数 JLabel label1;// 标签1:“输入一个1到100之间的整数” JLabel label2;// 标签2:“提示” JLabel label3;// 标签3:提示的内容(偏大、偏小、正确) JButton buttonOfSure;// 确定按钮 JButton buttonOfExit;// 退出按钮 JTextField jTextField;// 猜数输入单行文本框 public void init() { // 窗体的定义 this.setTitle(\"这是一个猜数游戏\"); this.setSize(400, 120); this.setResizable(false); this.setLayout(new GridLayout(3, 2)); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 随机数 Random random = new Random(); numberOfRandom = random.nextInt(100); // 各组件的定义 label1 = new JLabel(\"请输入一个1到100之间的整数:\"); label2 = new JLabel(\"提示:\", SwingConstants.CENTER); label3 = new JLabel(\"猜猜看\"); buttonOfSure = new JButton(\"确定\"); this.getRootPane().setDefaultButton(buttonOfSure);// 默认用户按下回车键触发“确定”按钮 buttonOfSure.addActionListener(this); buttonOfExit = new JButton(\"退出\"); buttonOfExit.addActionListener(this); jTextField = new JTextField(\"输入\"); // 窗体加入各组件 this.add(label1); this.add(jTextField); this.add(label2); this.add(label3); this.add(buttonOfSure); this.add(buttonOfExit); // 显示窗体 this.setVisible(true); System.out.println(numberOfRandom);// 偷偷看看随机数,哈哈 } // 事件处理 public void eventHandle() { //捕获非整型输入异常 try { numberOfUser = Integer.parseInt(jTextField.getText());//获得用户输入数 if (numberOfUser < 1 || numberOfUser > 100) { JOptionPane.showMessageDialog(this, \"请输入1到100之间的整数\"); } else { if (numberOfUser > numberOfRandom) { label3.setText(\"偏大\"); jTextField.requestFocus();//清空文本框并使重新获得焦点 } if (numberOfUser < numberOfRandom) { label3.setText(\"偏小\"); jTextField.requestFocus(); } if (numberOfUser == numberOfRandom) { label3.setText(\"恭喜你,答对了。\"); jTextField.requestFocus(); } } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, \"请输入整数\", \"输入错误\", JOptionPane.WARNING_MESSAGE); jTextField.requestFocus(); } } //按钮触发选择 public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == \"确定\") { this.eventHandle(); } if (e.getActionCommand() == \"退出\") { System.exit(0); } } public static void main(String[] args) { new GuessNumber().init(); } } 运行结果: 7.练习使用JscrollPane。使用BorderLayout将JFrame布局分为左右两块;左边又使用 GridLayout,包含三个按钮,右边在JLabel里显示一幅图画,按钮控制JLabel是否显示滚动条。 //test9_7 import java.awt.BorderLayout; import java.awt.Button; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; public class test9_7 extends JFrame implements ActionListener { private JPanel jPanel;//左边panel框 private Button button1; private Button button2; private Button button3; private JScrollPane jscrollPane;//右边滚动框 private JLabel label;//滚动框中的标签 public ImageIcon picture = null;//标签中的图标 public boolean whetherCroll = true;//用于切换滚动条的显示 public void init() { JFrame jFrame = new JFrame(\"练习使用JscrollPane\"); Container pane = jFrame.getContentPane(); this.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE)); // 定义左边镶板JPanel框和三个按钮 jPanel = new JPanel(new GridLayout(3, 1, 0, 30)); button1 = new Button(\"滚动\"); button1.addActionListener(this); button2 = new Button(\"试试\"); button2.addActionListener(this); button3 = new Button(\"退出\"); button3.addActionListener(this); jPanel.add(button1); jPanel.add(button2); jPanel.add(button3); // 读取图片作为图标 picture = new ImageIcon(\"D:/image/fuck.jpg/\"); // 将图标赋给标签label label = new JLabel(picture); // 定义滚动框,总是显示滚动条 jscrollPane = new JScrollPane(label, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); // 将左右两边的中间容器放弃JFrame中 pane.add(jPanel, BorderLayout.WEST); pane.add(jscrollPane, BorderLayout.EAST); //排版显示 jFrame.pack(); jFrame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getActionCommand() == \"滚动\") { if (whetherCroll) { jscrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);//垂直不显示 jscrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);//水平不显示 whetherCroll = false; } else { jscrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);//垂直显示 jscrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//水平显示 whetherCroll = true; } } if (e.getActionCommand() == \"试试\") { JOptionPane.showMessageDialog(this, \"oh,,,Fuck your teacher? yeal……good!\"); } if (e.getActionCommand() == \"退出\") { System.exit(0); } } public static void main(String[] args) { new test9_7().init(); } } 运行结果: 显示滚动条 点击“滚动”按钮后,没显示滚动条 8.练习使用JList。建立两个JList,双击其中任何一个中的某一项,此项就会跑到另外一个JList中。 //test9_8 import java.awt.Container; import java.awt.GridLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; public class test9_8 extends JFrame implements MouseListener { public JFrame jFrame; public JList jList1; public JList jList2; public DefaultListModel listModel1; public DefaultListModel listModel2; public void init() { JFrame jFrame = new JFrame(\"练习使用List\"); Container pane = jFrame.getContentPane(); pane.setLayout(new GridLayout(1,2)); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); listModel1 = new DefaultListModel(); listModel1.addElement(\"First\"); listModel1.addElement(\"Second\"); listModel1.addElement(\"Third\"); listModel2=new DefaultListModel(); listModel2.addElement(\"one\"); listModel2.addElement(\"two\"); listModel2.addElement(\"three\"); jList1 = new JList(listModel1); jList2=new JList(listModel2); jList1.addMouseListener(this); jList2.addMouseListener(this); pane.add(jList1); pane.add(jList2); jFrame.pack(); jFrame.setVisible(true); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub if(e.getSource() == jList1){ int index = jList1.locationToIndex(e.getPoint()); Object o = jList1.getModel().getElementAt(index); listModel2.addElement(o); } if(e.getSource()==jList2){ int index = jList2.locationToIndex(e.getPoint()); Object o = jList2.getModel().getElementAt(index); listModel1.addElement(o); } } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public static void main(String[] args) { new test9_8().init(); } 运行结果: 9.练习使用JComboBox。包括一个JLable、一个JComboBox,可以通过输入或者选择JComboBox中的某一项来控制JLable中文字的大小。 //test9_9 import java.awt.Container; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class test9_9 extends JFrame implements ItemListener { public JFrame jFrame; private JLabel jLabel; private JComboBox jComboBox; private String[] fontSize = { \"8\", \"14\", \"20\", \"28\", \"32\", \"40\" }; public void init() { jFrame = new JFrame(\"练习ComboBox\"); Container container = jFrame.getContentPane(); container.setLayout(new GridLayout(2, 1)); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jLabel = new JLabel(\"你好吗?\"); jLabel.setFont(new Font(\"\", 0, 10));// 设置字体大小 jComboBox = new JComboBox(fontSize); jComboBox.setEditable(true);// 设置复选框可以输入 jComboBox.addItemListener(this);// 添加ItemListener监听 // 添加两个组件 container.add(jLabel); container.add(jComboBox); jFrame.pack();// 排版 jFrame.setVisible(true);// 显示 } public void itemStateChanged(ItemEvent e) { //使用这个判断的目的的是为了避免触发事件总是执行两次的问题 if (e.getStateChange() == ItemEvent.SELECTED) { try { String s = jComboBox.getSelectedItem().toString(); int intFontSize = Integer.parseInt(s); jLabel.setFont(new Font(\"\", 0, intFontSize)); // System.out.println(intFontSize); } catch (NumberFormatException r) { JOptionPane.showMessageDialog(this, \"请输入整数\"); } } } public static void main(String[] args) { new test9_9().init(); } } 运行结果: 10.练习使用JTable。包括姓名、学号、语文成绩、数学成绩、总分五项,单击总分会自动将语文数学成绩相加。 import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class Test9_10 extends JFrame implements MouseListener { private JTable jTable; private Object[][] cellData = { { \"姓名\", new String(\"林楚金\") }, { \"学号\", new String(\"200905\") }, { \"语文成绩\", new String(\"86\") }, { \"数学成绩\", new String(\"96\") }, { \"总分\", new String(\"点击出总分\") } }; private String[] columnNames = { \"col1\", \"col2\" }; public Test9_10() { DefaultTableModel model = new DefaultTableModel(cellData, columnNames) { public boolean isCellEditable(int row, int column) { return false; } }; jTable = new JTable(model); jTable.addMouseListener(this); this.add(jTable); this.setTitle(\"表格演示\"); this.setSize(300, 350); this.setLocation(200, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public void mouseClicked(MouseEvent e) { DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel(); int row = jTable.getSelectedRow(); int column = jTable.getSelectedColumn(); if(row==4 && column==1){ String yuwen = (String) tableModel.getValueAt(2, column);//语文成绩 String shuxue = (String) tableModel.getValueAt(3, column);//数学成绩 Integer count = Integer.parseInt(yuwen)+Integer.parseInt(shuxue); tableModel.setValueAt(count.toString(), row, column); } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public static void main(String[] args) { new Test9_10(); } 运行结果: 11.练习使用对话框。包括一个JLable和两个JButton,按任何一个JButton都会产生一个对话框,按确定后将输入内容在JLable中显示出来。 //test9_11 import java.awt.Container; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class test9_11 extends Frame implements ActionListener { JFrame jFrame; JButton jButton1; JButton jButton2; JLabel jLabel; public void init() { JFrame jFrame = new JFrame(\"练习使用对话框\"); Container pane = jFrame.getContentPane(); pane.setLayout(new GridLayout(3, 1)); jButton1 = new JButton(\"按钮1\"); jButton1.addActionListener(this); jButton2 = new JButton(\"按钮2\"); jButton2.addActionListener(this); jLabel = new JLabel(); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pane.add(jButton1); pane.add(jButton2); pane.add(jLabel); jFrame.pack(); jFrame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getActionCommand() == \"按钮1\" || e.getActionCommand() == \"按钮2\") { String s = JOptionPane.showInputDialog(this, \"\", \"请输入\"); jLabel.setText(s); } } public static void main(String[] args) { new test9_11().init(); } } 运行结果: 13.编写一个图形用户界面,包括三个JSlider对象和三个JTexField对象。每个JSlider代表颜色中的红、绿、蓝三部分,它们的值从0到255,在相应的JTextField中显示各个JSlider的 当前值。用这三个值作为Color类构造方法的参数创建一个新的Color对象,用来填充一个矩形。 import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class Test9_13 extends JFrame implements ChangeListener { private JTextField textField1; private JTextField textField2; private JTextField textField3; private JLabel label1; private JLabel label2; private JLabel label3; private JSlider slider1; private JSlider slider2; private JSlider slider3; private MyPanel myPanel; public Test9_13() { this.setTitle(\"JSliderDemo\"); this.setSize(200, 200); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLayout(new GridLayout(4, 3)); this.label1 = new JLabel(\"红\"); this.label2 = new JLabel(\"绿\"); this.label3 = new JLabel(\"蓝\"); this.textField1 = new JTextField(5); this.textField2 = new JTextField(5); this.textField3 = new JTextField(5); this.slider1 = new JSlider(JSlider.HORIZONTAL, 0, 255, 125); this.slider2 = new JSlider(JSlider.HORIZONTAL, 0, 255, 125); this.slider3 = new JSlider(JSlider.HORIZONTAL, 0, 255, 125); this.add(label1); this.add(slider1); this.add(textField1); this.add(label2); this.add(slider2); this.add(textField2); this.add(label3); this.add(slider3); this.add(textField3); this.myPanel = new MyPanel(); this.add(myPanel); this.slider1.addChangeListener(this); this.slider2.addChangeListener(this); this.slider3.addChangeListener(this); } public void stateChanged(ChangeEvent event) { if ((JSlider) event.getSource() == this.slider1) { String str = \"\" + this.slider1.getValue(); this.textField1.setText(str); } if ((JSlider) event.getSource() == this.slider2) { String str = \"\" + this.slider2.getValue(); this.textField2.setText(str); } if ((JSlider) event.getSource() == this.slider3) { String str = \"\" + this.slider3.getValue(); this.textField3.setText(str); } this.myPanel.setColor(new Color(this.slider1.getValue(), this.slider2 .getValue(), this.slider3.getValue())); this.myPanel.repaint(); } public static void main(String[] args) { new Test9_13(); } } class MyPanel extends JPanel { private Color color = Color.CYAN; public void paint(Graphics g) { g.setColor(this.color); g.fillRect(0, 0, 200, 200); } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } } 运行结果: 14.编写Application程序,构造一CUI,实现对两个数的相加、减、乘、除功能。用含有三个JTextField、一个JButton、三个JTextField分别用于输入两个数字和运算符号,结果用JLable显示出来。 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test9_14 extends JFrame implements ActionListener { private JLabel jl1, jl2, jl3, jl4; private JTextField jtf1, jtf2, jtf3; private JButton jb; public Test9_14() { this.jl1 = new JLabel(\"数字1\"); this.jl2 = new JLabel(\"符号\"); this.jl3 = new JLabel(\"数字2\"); this.jl4 = new JLabel(); this.jtf1 = new JTextField(); this.jtf2 = new JTextField(); this.jtf3 = new JTextField(); this.jb = new JButton(\"结果\"); this.jb.addActionListener(this); this.setLayout(new GridLayout(3, 3)); this.add(jl1); this.add(jl2); this.add(jl3); this.add(jtf1); this.add(jtf2); this.add(jtf3); this.add(jb); this.add(jl4); this.setTitle(\"加减乘除\"); } } this.setSize(250, 100); this.setLocation(200, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); public void actionPerformed(ActionEvent e) { float n1 = 0; float n2 = 0; } public static void main(String[] args) { } new Test9_14(); System.out.println(\"输入符号为:\" + this.jtf2.getText()); n1 = Float.parseFloat(this.jtf1.getText()); n2 = Float.parseFloat(this.jtf3.getText()); if (this.jtf2.getText().equals(\"+\")) { this.jl4.setText(\"结果为:\" + (n1 + n2)); } else { } if (this.jtf2.getText().equals(\"-\")) { this.jl4.setText(\"结果为:\" + (n1 - n2)); } else { if (this.jtf2.getText().equals(\"*\")) { this.jl4.setText(\"结果为:\" + (n1 * n2)); } else { if (this.jtf2.getText().equals(\"/\")) { this.jl4.setText(\"结果为:\" + (n1 / n2)); } else { this.jl4.setText(\"输入有误!\"); } } } 运行结果: 15.扩充上一个练习,先弹出一对话框,输入密码正确,方能进行计算界面。 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Test9_15 extends JFrame implements ActionListener { private JLabel jl1, jl2, jl3, jl4; private JTextField jtf1, jtf2, jtf3; private JButton jb; public Test9_15() { this.jl1 = new JLabel(\"数字1\"); this.jl2 = new JLabel(\"符号\"); this.jl3 = new JLabel(\"数字2\"); this.jl4 = new JLabel(); this.jtf1 = new JTextField(); this.jtf2 = new JTextField(); this.jtf3 = new JTextField(); } this.jb = new JButton(\"结果\"); this.jb.addActionListener(this); this.setLayout(new GridLayout(3, 3)); this.add(jl1); this.add(jl2); this.add(jl3); this.add(jtf1); this.add(jtf2); this.add(jtf3); this.add(jb); this.add(jl4); this.setTitle(\"加减乘除\"); this.setSize(250, 100); this.setLocation(450, 300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); \"); public void actionPerformed(ActionEvent e) { float n1 = 0; float n2 = 0; } public static void main(String[] args) { String inputValue = JOptionPane.showInputDialog(\"请输入密码(我爱苍老师): System.out.println(\"输入符号为:\" + this.jtf2.getText()); n1 = Float.parseFloat(this.jtf1.getText()); n2 = Float.parseFloat(this.jtf3.getText()); if (this.jtf2.getText().equals(\"+\")) { this.jl4.setText(\"结果为:\" + (n1 + n2)); } else { } if (this.jtf2.getText().equals(\"-\")) { this.jl4.setText(\"结果为:\" + (n1 - n2)); } else { } if (this.jtf2.getText().equals(\"*\")) { this.jl4.setText(\"结果为:\" + (n1 * n2)); } else { if (this.jtf2.getText().equals(\"/\")) { } this.jl4.setText(\"结果为:\" + (n1 / n2)); } else { } this.jl4.setText(\"输入有误!\"); while(!inputValue.equals(\"我爱苍老师\")){ JOptionPane.showMessageDialog(null, \"密码错误\提示\JOptionPane.ERROR_MESSAGE); inputValue = JOptionPane.showInputDialog(\"请输入密码(我爱苍老师):\"); break; } new Test9_15(); } } 运行结果: 因篇幅问题不能全部显示,请点此查看更多更全内容