Java核心技术习题答案_第1页
Java核心技术习题答案_第2页
Java核心技术习题答案_第3页
Java核心技术习题答案_第4页
Java核心技术习题答案_第5页
已阅读5页,还剩79页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Java核心技术习题答案马志强张然李雷孝编清华大学出版社目录 TOC o 1-5 h z 第一章Java语言概述3第二章Java语法基础4第三章面向对象编程15第四章数组38第五章高级类特性45第六章GUI编程51第七章集合框架62第九章集合框架77第十章IO流81第十一章JDBC访问数据库84第十二章线程8590第十三章网络编程90第一章Java语言概述一、选择题1-5 ABBBB6-8 AAB二、填空题MyClassString 数组(String口) 一javac java A三、程序设计题1、搭建Java运行环境,并写一个Java程序打印输出“开始学习Java程序设计! ”。1)首先安

2、装JDK;2)配置环境变量path,classpath可配可不配;3)public class HelloWorldpublic static void main(String args)开始学习Java程序设计!);)2、修改下面四个Java源文件中的错误,使其能够编译和运行。:TestAnotherl类不能再使用public修饰,一个源文件中只能有一个类或者接口用 public 修饰;:源文件中public修饰的类的名字为Testing2,和源文件名字不一致;:Test3类的main方法的形参类型为String口 ;:Test4类的main方法必须使用static关键字修饰。第二章Java

3、语法基础一、选择题1-5 BCADB6-9 DCCC二、填空题. abc , a1, _abc, _1a, ab123#a, const, $abc, 1abc, if, $#1sa, $_a, _$q1.题目出现问题:代码修改为ch = (char) (ch+1);结果为B;如果直接结果为 98。(真)false(假)5. 2 2 false 2*20/100 (double)m*20/100三、编程题1、由命令行输入一个成绩,使用switch结构求出成绩的等级。A: 90-100; B: 80- 89; C: 70-79; D: 60-69; E: 0-59。public class If

4、ElseTest public static void main(String args) Scanner sc = new Scanner;int grade =();if(grade100)(0);)int temp =(int)(grade/10);switch(temp)case 10:break;)case 9:break;)case 8:break;)case 7:break;) case 6:break;)default:break;)2、计算圆周率:PI = 4 4/3+4/5-4/7;打印出第一个大于小于的值。public class PITestpublic static

5、void main(String args)double result=;for(int i=1;i+)double m=(2*i-1);if(i%2)=0)result-=m;else(result+=m;if(result & resultbreak;)3、输入一个数据n,计算斐波那契数列(Fibonacci)的第n个值。斐波那契数列:1、1、 2、 3、 5、 8、 13、 21、 34、。public class FibonacciTestpublic static void main(String args)Scanner sn=new Scanner;int num=();int

6、i=1;int n1=1,n2=1;while(i=num)if(i=1|i=2)n2=1;else(int temp=n2;n2=n1+n2;n1=temp;)i+;)第+num+个值为:+n2);)4、计算多项式1-1/3+1/5-1/7+1/9的值。1)要求出前50项和值。2)要求出最后一项绝对值小于1e-5的和值。public class SumTestpublic static void main(String args) double sum=;for(int i=1;i=50;i+)if(i%2=0)sum=(2*i-1);else(sum=sum+(2*i-1);)前50项和值

7、:+sum);double item=;int j=1;sum=;while(itemitem=(2*j-1);if(j%2=0)sum-=item;else(sum+=item;)j+;)最后一项绝对值小于1e-5的和值:+sum);5、产生100个0-999之间的随机整数,然后判断这100个随机整数哪些是素数,哪些不 是public class PrimeTest public static void main(String args) PrimeTest t = new PrimeTest();for(int i=0;i100;i+)int num = (int)()*1000);if(

8、num)是素数! );else(不是素数! );)public boolean isPrime(int num)for(int i=2;i=num/2;i+)if(num%i=0)第一个被+i+整除! ); return false;)return true;)6、在屏幕上打印出n行的金字塔图案,如,若n=3,则图案如下:*public class PrintStarpublic static void main(String args)Scanner sn=new Scanner;int rows=();for(int i=1;i=rows;i+)for(int j=1;j=rows-i;j

9、+)for(int k=1;k=2*i-1;k+)7、歌德巴赫猜想,任何一个大于六的偶数可以拆分成两个质数的和,打印出所有的可 能。如输入10,结果为:10=5+5; 10=3+7。public class Gede public static void main(String args) int n = (args0);if(n=6 | n%2!=0)错误的参数! );return;)Gede g = new Gede();ava。public class CalenderModelA(ava。public class TestCalenderModelApublic static void

10、 main(String args)(Scanner scan = new Scanner;请输入年份:);int year =();请输入月份:);int month =();月历如下);CalenderModelA testBegin = new CalenderModelA();(year, month);)第三章面向对象编程一、选择题1-5 CABDD2-10 DCCBC11-12 CC二、填空题.Package mypackage;.final3.Object.package import class. c三、程序设计题2、按下列要求编写程序:创建Teacher类double要求:T

11、eacher类要描述姓名、年龄、薪水,类型分别为String、int、double创建TeacherTest类要求:在TeacherTest类中创建Teacher的对象;为该对象的属性(姓名、性别、 年龄)赋值;将该对象的属性(姓名、性别、年龄)输出;为Teacher类添加一个方法,用于在教师原有薪水的基础上增加5000;修改TeacherTest类,增加对教师增加薪水方法的调用,并将增加后的薪水值输 出。:public class Teacher public String name;public int age;public double salary;public String getN

12、ame() return name;)public void setName(String name) =name;)public int getAge() return age;)public void setAge(int age) =age;public double getSalary() return salary;)public void setSalary(double salary) =salary;)public Teacher()public Teacher(String name,int age,double salary)=name;=age;=salary;)publ

13、ic void addSalary()=+5000;public class TeacherTest public static void main(String args) Teacher teacher=new Teacher();=35;一 i=zhangsan;=;();)3、定义一个Person类。包含以下属性:String name; int age; boolean gender; Person partner。定义marry(Person p)方法,代表当前对象和p结婚,如若可以结婚,则输出恭 贺信息,否则输出不能结婚原因。下列情况不能结婚:结婚年龄,男24,女22; 3,某

14、一方已婚。定义测试类,来测试以上程序。public class Personprivate String name;private int age;private boolean gender;Person partner;public Person(String name,int age,boolean gender,Person partner)=name;=age;=gender;=partner;)public void marry(Person p)if=同性不能结婚! );return;)if(=true & 24)|=false & 22)| =true & 24) | =fal

15、se & 22)没有达到结婚年龄! );return;)if!=null | !=null)有一方已经结婚! );return;)祝你们新婚愉快! );=p;=this;)public static void main(String args)Person p1=new Person(关之琳,23,false,null);Person p2=new Person(刘德华,26,true,null);Person p3=new Person(孙楠,70,true,null);(p2);(p3);)4、定义一个Animal类,该类有两个私有属性,name(代表动物的名字)和legs (代表动物 的

16、腿的条数)。两个构造方法,一个无参,默认给name赋值为AAA,给legs赋值为4;另一个需要 两个参数,分别用这两个参数给私有属性赋值。两个重载的move()方法,其中一个无参,在屏幕上输出一行文字:XXX Moving!(XXX为该动物的名字);另一个需要一个int参数n,在屏幕上输出n次XXX Moving!public class Animal1 private String name;private int legs;public Animal1()二AAA;=4;)public Animal1(String name,int legs)super();=name;=legs;)pu

17、blic String getName() return name;)public void setName(String name) = name;public int getLegs() return legs;)public void setLegs(int legs) =legs;)public void move()public void move(int n)int i=1;while(i=n)i+;)5、定义一个Fish类,继承自Animal类。提供一个构造方法,该构造方法需要一个参数name,并给legs赋默认值 0;覆盖Animal类中的无参move()方法,要求输出:XXX

18、 Swimming!public class Fish extends Animal private String name;private int legs;public Fish(String name)=name;=0;)public void move()public class Bird extends Animal private String name;private int legs;public Bird(String name)=name;=2;) public void move()6、写一个类Zoo,要求分别生成若干个Animal、Fish和Bird。并调用他们的属性和

19、方 法。public class Zoo public static void main(String args) Animal a=new Animal(dog”,4);();(3);Fish f=new Fish(small fish);();Bird b=new Bird(xique);();Animal af=new Fish(small fish);();)7、某公司的雇员分为以下若干类:Employee:这是所有员工总的父类,属性:员工的姓名,员工的生日月份。方法: getSalary(int month)根据参数月份来确定工资,如果该月员工过生日,则公司会额外 奖励100元。Sa

20、lariedEmployee: Employee的子类,拿固定工资的员工。属性:月薪;HourlyEmployee: Employee的子类,按小时拿工资的员工,每月工作超出160小 时的部分按照倍工资发放。属性:每小时的工资、每月工作的小时数;SalesEmployee: Employee的子类,销售人员,工资由月销售额和提成率决定。属 性:月销售额、提成率。BasedPlusSalesEmployee: SalesEmployee的子类,有固定底薪的销售人员,工资 由底薪加上销售提成部分。属性:底薪。写一个程序,把若干各种类型的员工放在一个Employee数组里,写一个函数,打印出某 月每

21、个员工的工资数额。注意:要求把每个类都做成完全封装,不允许非私有化属性。class Employeeprivate String name;private int month;public Employee(String name,int month)=name;=month;)public String getName()return name;public double getSalary(int month)if=month)return ;) return ;)class SalariedEmployee extends Employeeprivate double monthSala

22、ry;public SalariedEmployee(String name,int month,double monthSalary) super(name,month);=monthSalary;)public double getSalary(int month) return monthSalary+(month);)class HourlyEmployee extends Employeeprivate int hours;private double hourSalary;public HourlyEmployee(String name,int month,int hours,d

23、ouble hourSalary)super(name,month);=hours;=hourSalary;)public double getSalary(int month)double result;if(hours=160)result=hours*hourSalary;else(result=160*hourSalary+(hours-160)*hourSalary;)return result+(month);)class SalesEmployee extends Employeeprivate double salesCount;private double rate;publ

24、ic SalesEmployee(String name,int month,double salesCount,double rate)super(name,month);=salesCount;=rate;)public double getSalary(int month)return salesCount*rate+(month);)class BasedPlusSalesEmployee extends SalesEmployee private double basedPlus;public BasedPlusSalesEmployee(String name,int month,

25、double salesCount,double rate,double basedPlus)super(name,month,salesCount,rate);=basedPlus;)public double getSalary(int month)return basedPlus+(month);)public class EmployeeTestpublic static void main(String args)Employee e=new Employee4;e0=new SalariedEmployee(zhangsan”,9,;e1=new HourlyEmployee(li

26、si”,5,230,;e2=new SalesEmployee(wangwu”,11,;e3=new BasedPlusSalesEmployee(zhaoliu”,2,;for(int i=0;i;i+)月份的工资总额为:+ei.getSalary(9);)四、实训题班级成绩管理系统实体类设计。public class Test public static void main(String args)(信息工程学院);(软件工程);(软件 10-1);Grade stugrade =new Grade();(Web程序设计);(2011-2012(下);().addGrade(stugrad

27、e);stugrade =new Grade();ddGrade(stugrade);stugrade =new Grade();ddGrade(stugrade);stugrade =new Grade();ddGrade(stugrade);stugrade =new Grade();ddGrade(stugrade);stugrade =new Grade();ddGrade(stugrade);stugrade =new Grade();ddGrade(stugrade);stugrade =new Grade();ddGrade(stugrade);(2011-2012(下); ()

28、.sortByxq();public class Studentprivate String sid;private String sname;private String xueyuan;oString();autoId();grades = new GradeArray();)public Student(String sid) this(sid,null);)public Student(String sid,String sname) this(sid,sname,null);)public Student(String sid,String sname,String xueyuan)

29、 =sid;=sname;=xueyuan;grades = new GradeArray();public String getSid() return sid;)public void setSid(String sid) =sid;)public String getSname() return sname;)public void setSname(String sname) =sname;)public String getXueyuan() return xueyuan;)public void setXueyuan(String xueyuan) = xueyuan;public

30、 String getZhuanye() return zhuanye;)public void setZhuanye(String zhuanye) =zhuanye;)public String getBanji() return banji;)public void setBanji(String banji) =banji;)public GradeArray getGrades() return grades;)public void setGrades(GradeArray grades) =grades;)public ZcGrade getZcGrade() return zc

31、Grade;)public void setZcGrade(ZcGrade zcGrade) =zcGrade;)public void computeZc(String xqid)zcGrade = new ZcGrade(xqid);float sum = 0;for(int i=0;i0)Grade temp = gradesj+1;gradesj+1 = gradesj; gradesj = temp;)public class GradeListStack /* param args*/private Stack gradelist;GradeListStack()gradelist

32、 = new Stack();)public void push(Grade grade)(grade);)public Grade pop()return ();)public boolean isEmpty()return ();)public Stack getGradelist() return gradelist;)public void setGradelist(Stack gradelist) =gradelist;) Overridepublic String toString() s=180iarrjarrj=arriarri=temp三、程序设计题(1)写一个类在其中定义一

33、些方法实现数组元素的遍历、排序、插入、删除、查 找。public class ArrayTestpublic static void main(String args)int口 a=11,2,-3,54,115,36;int口 b=110,-9,78,27,6,225,94,32,-12,1111,0;,+,=;/*计算器上的功能键的显示名字*/private final String口 COMMAND = Backspace, CE, C );/*计算器左边的M的显示名字*/private final String口 M = , MC, MR, MS, M+ ;/*计算器上键的按钮*/pri

34、vate JButton keys = new JButton口;/*计算器上的功能键的按钮*/private JButton commands = new JButton;/*计算器左边的M的按钮*/private JButton m = new JButton口;/*计算结果文本框*/private JTextField resultText = new JTextField(0);etForeground;)etForeground;keys8.setForeground;keys13.setForeground;keys18.setForeground;keys19.setForegr

35、ound;etForeground;)etForeground;)etLayout(new BorderLayout(3, 5);getContentPane().add(North,top);getContentPane().add(Center,panel1);getContentPane().add(West,calmsPanel);ddActionListener(this);)for (int i = 0; i ; i+) commandsi.addActionListener(this);for (int i = 0; i = 0) )& ().indexOf(.) 0) ; el

36、se if (!(.)(oubleValue(); catch (NumberFormatException e) )return result;)public static void main(String args口) (Calculator calculatorl = new Calculator();(true);第七章集合框架一、选择题1-2 BC二、填空题一、元素个数二、无序可重复 有可以 无 不可以key-value映射 value key三、覆盖添加 1 key 获得 key 对应的 value keySet set valuesCollection entrySet 三、程序

37、设计题写MyStack类,实现栈功能,要求在类中使用ArrayList保存数据。写 MyStackTest类对栈功能进行测试。import .*;public class MyStack(private ArrayList data;public MyStack()data = new ArrayList();public void push(Object o) (o);)public Object pop() int size =();if(size0)return ()-1);elsereturn null;)public int getSize() return ();)public c

38、lass MyStackTest(public static void main(String args)MyStack stack = new MyStack();(new Integer(l);(new Integer(2);(new Integer(3);(new Integer(4);(new Integer(5);)写MyQueue类,实现队列功能,要求在类中使用ArrayList保存数据。写 MyQueueTest类对队列功能进行测试。import .*;public class MyQueue(private ArrayList data;public MyQueue()data

39、 = new ArrayList();)public void in(Object o)(o);public Object out()int size =();if(size0)return (0);elsereturn null;)public int getSize() return ();)public class MyQueuTest(public static void main(String args)(MyQueue queue = new MyQueue();(new Integer(1);(new Integer(2);(new Integer(3);(new Integer

40、);(new Integer(5);)使用 TreeSet 和 Comparator,编写 TreeSetTestInner 类,要求对 TreeSet 中的元 HashSet ArrayList、TreeMap、HashMap、TreeSet、LinkedList进行升 序和倒序排列,并使用匿名内部类和静态内部类分别实现。import .*;public class TreeSetTestInnerpublic static void main(String args) TreeSet c = new TreeSet(new MyComparator();(HashSet);(ArrayLi

41、st);(TreeMap);(HashMap);(TreeSet);(LinkedList);Iterator it =();while()static class MyComparator implements Comparator public int compare(Object o1, Object o2)String si = (String)ol;String s2 = (String)o2; ;public class TreeSetTestInner2public static void main(String args) TreeSet c = new TreeSet(new

42、 Comparator()public int compare(Object ol, Object o2)String si = (String)ol;String s2 = (String)o2; ;public class TreeSetTestpublic static void main(String args) TreeSet c = new TreeSet(new MyComparator();(HashSet);(ArrayList);(TreeMap);(HashMap);(TreeSet);(LinkedList);Iterator it =();while()TreeSet

43、 cc = new TreeSet(new MyComparator2();for(int i=1; itype2)return -1;else if(type1num2)return -1;else if(num1num2)return 1;else if(num1num2) return -1;) return 0;q bfibm!曲岫q 浊:dojtieg Md小 : dniiq bfibm!曲岫q 浊:dojtieg Md小 : dnii白伯:dodjk1n 诅旭:4力加):*cd. szM电33 jAaorl(aJ &Lr“ dxk孙 vdd才孑曲扇!肌mdw4 d?pwi(m.J

44、*narl : dbubkj : bwJean4 tnuji; dzutkl; Inde的事-e-eaijtibb dwcfngJtcarh)nbbm! dxttri urd* j daiib/! v3d靖帕打中画皿:由山口; bed的Cashiurra MBirfc;! M 珅Ha nm ”fng* KHiir(nniiTrii! 3mgJ! vod小 甲忙murilkn rebi! IN); Jccait8 gAzutlJ i 皿刈。触M0Ulin才式QTl : k(Ul): 4id小用&阴 I);繁因Xkq ifitoneri ;&Q cuJiim ;irJ#QeileRi4(l:制#

45、iddOLtl-snfffinouIwi? ;: Wmh4 qdGjiJaieilri rdei; iril; Qd.nrm类结构如图7-9所示。图7-9类图结构将类结构以代码形式表示,并对方法和构造器提供合理的实现;使用TestBanking类对代码进行测试。public class Account(protected double balance;public Account(double balance)=balance;)public boolean deposit(double amount)balance += amount;return true;)public boolean

46、withdraw(double amount) if(amount=1 & index=custNum)return (Customer)(new Integer(index); elsereturn null;)public HashMap getAllCustomer()return customers;)public int getCustomerNum()return custNum;public class CheckingAccount extends Account(private double overdraft;public CheckingAccount(double ba

47、lance, double overdraft) super(balance);=overdraft;)public CheckingAccount(double balance) this(balance, ;)public boolean withdraw(double amount) if(amount=balance)balance -= amount;return true;else if(amount=balance+overdraft)overdraft -= (amount-balance);balance = 0;return true;elsereturn false;)p

48、ublic double getOverdraft() return overdraft;)import .*;public class Customer(private String name;private ArrayList accounts = new ArrayList();public Customer(String name)=name;)public String getName()return name;) public void addAccount(Account account)(account);)public Account getAccount(int index

49、) return (Account)(index-1);)public ArrayList getAllAccount() return accounts;)public class SavingAccount extends Account(private double rate;public SavingAccount(double balance, double rate) super(balance);=rate;)import .*;public class TestBankingpublic static void main(String args)(Bank bank = new

50、 Bank();(new Customer(steven);(new Customer(kevin);Customer cust1 = (1);Customer cust2 = (2);(new SavingAccount,);(new CheckingAccount,);(new CheckingAccount,);Account acc1 = (1);CheckingAccount acc2 = (CheckingAccount)(2);CheckingAccount acc3 = (CheckingAccount);第九章集合框架一、选择题1-5 AABAA6 A二、填空题catchEr

51、ror Exception.指定类或接口不存在.默认处理程序三、程序设计题按要求完成下题:编写OwnException类,要求继承Exception类;编写 OwnExceptionSource 类,要求包含方法 a(),a()抛出 OwnException;编写OwnExceptionHandler类,要求包含main(),在main()中调用OwnExceptionSource类的a(),并处理相关异常。public class OwnException extends Exception public OwnException() this(My Own Exception happen

52、ed!);)public OwnException(String msg) super(msg);)public class OwnExceptionSourcepublic void a() throws OwnExceptionthrow new OwnException();)public class OwnExceptionHandler public static void main(String args) OwnExceptionSource es = new OwnExceptionSource();try();catch(Exception e) ();finally )编写

53、DivisionByZer。类,包含:division。:要求执行10/0操作,并使用异常处理机制处理产生的异常;main(): 调用 division。;修改division。:执行10/0不变,但不在方法中处理产生的异常,改将异 常抛出;修改main():调用division。并处理其抛出的异常。public class DivisionByZero(public static void Division()int a = 10;int b = 0;try(catch(ArithmeticException e)finally)public static void main(String

54、args)/*DivisionByZero d = new DivisionByZero();();*/new DivisionByZero().Division();)程序代码如下:public class TestExceptionpublic static void main(String args)要求修改程序,要求:在命令行输入参数不能满足输出要求时,会抛出相应异常,使 用异常处理机制处理抛出的异常。public class TestException(public static void main(String args)try catch(ArrayIndexOutOfBound

55、sException e)();)第十章IO流一、选择题1-5 DAACA6-10 CADBC11-15 DACCD16-17 DC二、填空题上二、输入流输出流write字节流 字符流 InputStream,OutputStream;Reader,Writer readwriteInputStream Writer byte口 String五、New FileWriter(”);六、屏幕七、键盘八、isDirectory () String口 list()九、readLine() ()三、程序设计题(2)编写FileCopy类,要求将1个文件的内容同时复制成多个文件。使用命令行完成文 件名的输入。public class FileCopy public static void main(String args) try (加载JDBCDriver获得与数据库的物理连接 创建不同类型的Statement执行SQL命令如果有结果集,处理结果集释放资源2.()“select sno, sname from Student”(sname”)三、实训题见附件。第十二章

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论