耿祥义-Java 2实用教程(3版)实验代码及答案4-8.pdf_第1页
耿祥义-Java 2实用教程(3版)实验代码及答案4-8.pdf_第2页
耿祥义-Java 2实用教程(3版)实验代码及答案4-8.pdf_第3页
耿祥义-Java 2实用教程(3版)实验代码及答案4-8.pdf_第4页
耿祥义-Java 2实用教程(3版)实验代码及答案4-8.pdf_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

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

文档简介

Java 2 实用教程 第三版 实验 指导与习题解答 实用教程 第三版 实验 指导与习题解答 实验模版代码及答案 实验模版代码及答案 1 2 目目 录录 上机实践上机实践 4 继承与接口继承与接口 3 实验 1 继承 3 实验 2 上转型对象 5 实验 接口回调 7 上机实践上机实践 5 字符串 时间与数字字符串 时间与数字 9 实验 1 STRING类的常用方法 9 实验 2 比较日期的大小 10 实验 3 处理大整数 11 上机实践上机实践 6 组件及事件处理组件及事件处理 12 实验 1 算术测试 12 实验 2 信号灯 15 实验 3 布局与日历 18 上机实践上机实践 7 组件及事件处理组件及事件处理 2 22 实验 1 方程求根 22 实验 2 字体对话框 25 实验 3 英语单词拼写训练 28 上机实践上机实践 8 多线程多线程 32 实验 1 汉字打字练习 32 实验 2 旋转的行星 34 实验 3 双线程接力 38 注 注 1 在你用的计算机上 找到可用的公共分区 一般为 在你用的计算机上 找到可用的公共分区 一般为 D 或或 E 盘 在其 中建自己的文件夹 如 盘 在其 中建自己的文件夹 如 LiXiaoLing 将自己编的程序均放在自建的文件夹内 便于管理 不要把程序保存在 将自己编的程序均放在自建的文件夹内 便于管理 不要把程序保存在 C 盘上 盘上 C 盘为系统盘 有大量的系统文件 并 且被保护 盘为系统盘 有大量的系统文件 并 且被保护 2 要有自己的优盘 以便保存未完成的程序和已编译运行成功的程序 要有自己的优盘 以便保存未完成的程序和已编译运行成功的程序 编译和解释运行工具配置表编译和解释运行工具配置表 序 号 工具 命令 安装路径作为参考 参数 初始目录捕获 输出 序 号 工具 命令 安装路径作为参考 参数 初始目录捕获 输出 1 JavaC 编译 c Program Files Java jdk1 6 0 bin javac exe FileName FileName FileDir FileDir 2 Java 运行 c Program Files Java jdk1 6 0 bin java exe FileNameNoExt FileNameNoExt FileDir FileDir 3 Appletviewer Web 浏览器 c Program Files Java jdk1 6 0 bin appletviewer exe FileName FileName FileDir FileDir 上机实践上机实践 4 继承与接口继承与接口 实验实验 1 继承继承 1 说明 说明 一个主类一个主类 People Demo 和一个父类和一个父类 Peopl 其他为子类 在主类 其他为子类 在主类 People Demo 中定义了各 子类 中定义了各 子类 ChinaPeople 子类 子类 BeijingPeople 子类和子类和 AmericanPeople 子类 的对象 继承关系 如下图 子类 的对象 继承关系 如下图 ChinaPeople 子类子类 AmericanPeople 子类子类 BeijingPeople 子类子类 People 父类父类 2 代码 代码 文件名 文件名 People Demo java class People protected double weight height public void speakHello System out println yayawawa public void averageHeight height 173 System out println average height height public void averageWeight weight 70 System out println average weight weight class ChinaPeople extends People 重写重写 public void speakHello 方法 要求输出类似 你好 吃了吗 这样的汉语信息方法 要求输出类似 你好 吃了吗 这样的汉语信息 public void speakHello System out println 你好你好 吃饭了吗吃饭了吗 重写重写 public void averageHeight 方法 要求输出类似方法 要求输出类似 中国人的平均身高 中国人的平均身高 168 78 厘米 这样的汉语信息厘米 这样的汉语信息 public void averageHeight height 173 System out println 中国人的平均身高 中国人的平均身高 height 厘米厘米 重写重写 public void averageWeight 方法 方法 要求输出类似 中国人的平均体重 要求输出类似 中国人的平均体重 65 公斤 这样的汉语信息公斤 这样的汉语信息 public void averageWeight 3 weight 67 34 System out println 中国人的平均体重 中国人的平均体重 weight 公斤公斤 public void chinaGongfu 输出中国武术的信息 例如 输出中国武术的信息 例如 坐如钟坐如钟 站如松站如松 睡如弓睡如弓 等等 System out println 坐如钟坐如钟 站如松站如松 睡如弓睡如弓 class AmericanPeople extends People 重写重写 public void speakHello 方法 要求输出类似 方法 要求输出类似 How do you do 这样的英语信息 这样的英语信息 public void speakHello System out println How do You do 重写重写 public void averageHeight 方法方法 public void averageHeight height 188 System out println Amerian Average height height cm 重写重写 public void averageWeight 方法方法 public void averageWeight weight 80 23 System out println Amerian Average weight weight kg public void americanBoxing System out println 直拳 钩拳直拳 钩拳 输出拳击的信息 例如 直拳 钩拳 等输出拳击的信息 例如 直拳 钩拳 等 class BeijingPeople extends ChinaPeople 重写重写 public void speakHello 方法 要求输出类似 您好 这样的汉语信息方法 要求输出类似 您好 这样的汉语信息 public void speakHello System out println 您好您好 重写重写 public void averageHeight 方法方法 public void averageHeight height 16 System out println 北京人的平均身高 北京人的平均身高 height 厘米厘米 重写重写 public void averageWeight 方法方法 public void averageWeight weight 6 System out println 北京人的平均体重 北京人的平均体重 weight 公斤公斤 public void beijingOpera System out println 京剧术语京剧术语 输出京剧的信息输出京剧的信息 4 public class People Demo public static void main String args ChinaPeople chinaPeople new ChinaPeople AmericanPeople americanPeople new AmericanPeople BeijingPeople beijingPeople new BeijingPeople chinaPeople speakHello americanPeople speakHello beijingPeople speakHello chinaPeople averageHeight americanPeople averageHeight beijingPeople averageHeight chinaPeople averageWeight americanPeople averageWeight beijingPeople averageWeight chinaPeople chinaGongfu americanPeople americanBoxing beijingPeople beijingOpera beijingPeople chinaGongfu 实验实验 2 上转型对象上转型对象 1 答案 答案 代码 1 public double earnings return 50000 456 代码 2 public double earnings return 12 2300 代码 3 public double earnings return 52 500 代码 4 for int i 0 i employee length i 5 salaries salaries employee i earnings 2 模板代码 模板代码 文件名 文件名 HardWork java abstract class Employee public abstract double earnings class YearWorker extends Employee 代码 1 重写 earnings 方法 class MonthWorker extends Employee 代码 2 重写 earnings 方法 class WeekWorker extends Employee 代码 3 重写 earnings 方法 class Company Employee employee double salaries 0 Company Employee employee this employee employee public double salariesPay salaries 0 代码 4 计算 salaries return salaries public class HardWork public static void main String args Employee employee new Employee 20 for int i 0 i employee length i if i 3 0 6 employee i new WeekWorker else if i 3 1 employee i new MonthWorker else if i 3 2 employee i new YearWorker Company company new Company employee System out println 公司年工资总额公司年工资总额 company salariesPay 实验 接口回调实验 接口回调 1 答案 答案 代码 1 public double computeWeight return 45 5 代码 2 public double computeWeight return 65 5 代码 3 public double computeWeight return 145 代码 4 for int k 0 k goods length k totalWeights totalWeights goods k computeWeight 2 模板代码 模板代码 文件名 文件名 Road java interface ComputerWeight public double computeWeight class Television implements ComputerWeight 代码 代码 1 实现实现 computeWeight 方法 方法 class Computer implements ComputerWeight 7 代码 代码 2 实现实现 computeWeight 方法 方法 class WashMachine implements ComputerWeight 代码 代码 3 实现实现 computeWeight 方法 方法 class Car ComputerWeight goods double totalWeights 0 Car ComputerWeight goods this goods goods public double getTotalWeights totalWeights 0 代码 代码 4 计算计算 totalWeights return totalWeights public class Road public static void main String args ComputerWeight goodsOne new ComputerWeight 50 goodsTwo new ComputerWeight 22 for int i 0 i goodsOne length i if i 3 0 goodsOne i new Television else if i 3 1 goodsOne i new Computer else if i 3 2 goodsOne i new WashMachine for int i 0 i 0 i System out print a i 实验实验 2 比较日期的大小比较日期的大小 模板代码模板代码 文件名 文件名 DateExample import java util import javax swing JOptionPane public class DateExample public static void main String args String str JOptionPane showInputDialog 输入第一个日期的年份输入第一个日期的年份 int yearOne Integer parseInt str str JOptionPane showInputDialog 输入该年的月份输入该年的月份 int monthOne Integer parseInt str str JOptionPane showInputDialog 输入该月份的日期输入该月份的日期 int dayOne Integer parseInt str str JOptionPane showInputDialog 输入第二个日期的年份输入第二个日期的年份 int yearTwo Integer parseInt str str JOptionPane showInputDialog 输入该年的月份输入该年的月份 int monthTwo Integer parseInt str str JOptionPane showInputDialog 输入该月份的日期输入该月份的日期 int dayTwo Integer parseInt str 10 Calendar calendar 代码 代码 1 初始化日历对象初始化日历对象 代码 代码 2 将将 calendar 的时间设置为的时间设置为 yearOne 年年 monthOne 月月 dayOne 日日 long timeOne 代码 代码 3 calendar 表示的时间转换成毫秒表示的时间转换成毫秒 代码 代码 4 将将 calendar 的时间设置为的时间设置为 yearTwo 年年 monthTwo 月月 dayTwo 日日 long timeTwo 代码 代码 5 calendar 表示的时间转换成毫秒 表示的时间转换成毫秒 Date date1 代码 代码 6 用用 timeOne 做参数构造做参数构造 date1 Date date2 代码 代码 7 用用 timeTwo 做参数构造做参数构造 date2 if date2 equals date1 System out println 两个日期的年 月 日完全相同两个日期的年 月 日完全相同 else if date2 after date1 System out println 您输入的第二个日期大于第一个日期您输入的第二个日期大于第一个日期 else if date2 before date1 System out println 您输入的第二个日期小于第一个日期您输入的第二个日期小于第一个日期 long days 代码 代码 8 计算两个日期相隔天数计算两个日期相隔天数 System out println yearOne 年年 monthOne 月月 dayOne 日和日和 yearTwo 年年 monthTwo 月月 dayTwo 相 隔相 隔 days 天天 实验实验 3 处理大整数处理大整数 模板代码模板代码 文件名 文件名 BigintegerExample import java math class BigIntegerExample public static void main String args BigInteger n1 new BigInteger 987654321987654321987654321 n2 new BigInteger 123456789123456789123456789 result null result 代码 代码 1 n1 和和 n2 做加法运算做加法运算 System out println 和和 result toString result 代码 代码 2 n1 和和 n2 做减法运算做减法运算 System out println 差差 result toString 11 result 代码 代码 3 n1 和和 n2 做乘法运算做乘法运算 System out println 积积 result toString result 代码 代码 4 n1 和和 n2 做除法运算做除法运算 System out println 商商 result toString BigInteger m new BigInteger 1968957 COUNT new BigInteger 0 ONE new BigInteger 1 TWO new BigInteger 2 System out println m toString 的因子有的因子有 for BigInteger i TWO pareTo m 0 5 12 operator else operator return operator public boolean getRight int answer if operator equals if answer numberOne numberTwo right true else right false else if operator equals if answer numberOne numberTwo right true else right false return right 文件名 文件名 ComputerFrame java import java awt import java awt event public class ComputerFrame extends Frame implements ActionListener TextField textOne textTwo textResult Button getProblem giveAnwser Label operatorLabel message Teacher teacher ComputerFrame String s super s teacher new Teacher setLayout new FlowLayout textOne 代码 代码 1 创建创建 textOne 其可见字符长是其可见字符长是 10 new TextField 10 textTwo 代码 代码 2 创建创建 textTwo 其可见字符长是其可见字符长是 10 new TextField 10 textResult 代码 代码 3 创建创建 textResult 其可见字符长是其可见字符长是 10 new TextField 10 operatorLabel new Label message new Label 你还没有回答呢你还没有回答呢 getProblem new Button 获取题目获取题目 giveAnwser new Button 确认答案确认答案 add getProblem add textOne add operatorLabel add textTwo 13 add new Label add textResult add giveAnwser add message textResult requestFocus textOne setEditable false textTwo setEditable false 代码 代码 4 将当前窗口注册为将当前窗口注册为 getProblem 的的 ActionEvent 事件监视器事件监视器 代码 代码 5 将当前窗口注册为将当前窗口注册为 giveAnwser 的的 ActionEvent 事件监视器事件监视器 代码 代码 6 将当前窗口注册为将当前窗口注册为 textResult 的的 ActionEvent 事件监视器事件监视器 getProblem addActionListener this giveAnwser addActionListener this textResult addActionListener this setBounds 100 100 450 100 setVisible true validate addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 public void actionPerformed ActionEvent e if 代码 代码 7 判断事件源是否是判断事件源是否是 getProblem int number1 teacher giveNumberOne 100 int number2 teacher giveNumberTwo 100 String operator teacher givetOperator textOne setText number1 textTwo setText number2 operatorLabel setText operator message setText 请回答请回答 textResult setText null if 代码 代码 8 判断事件源是否是判断事件源是否是 giveAnwser String answer textResult getText try int result Integer parseInt answer if teacher getRight result true message setText 你回答正确你回答正确 14 else message setText 你回答错误你回答错误 catch NumberFormatException ex message setText 请输入数字字符请输入数字字符 textResult requestFocus validate 文件名 文件名 MainClass java public class MainClass public static void main String args ComputerFrame frame frame 代码 代码 9 创建窗口 其标题为 算术测试创建窗口 其标题为 算术测试 实验实验 2 信号灯信号灯 2 模板代码 模板代码 文件名 文件名 SignalCanvas java import java awt public class SignalCanvas extends Canvas int red green yellow x y r SignalCanvas setBackground Color white public void setRed int r red r public void setGreen int g green g public void setYellow int y yellow y public void setPosition int x int y this x x this y y 15 public void setRadius int r this r r public void paint Graphics g if red 1 g setColor Color red else if green 1 g setColor Color green else if yellow 1 g setColor Color yellow g fillOval x y 2 r 2 r 文件名 文件名 SignalFrame java import java awt import java applet import java awt event public class SignalFrame extends Frame implements ItemListener Choice choice SignalCanvas signal null String itemRed 红灯红灯 itemYellow 黄灯黄灯 itemGreen 绿灯绿灯 public SignalFrame choice 代码 代码 1 创建创建 choice 代码 代码 2 创建创建 choice 添加添加 itemRed 代码 代码 3 创建创建 choice 添加添加 itemYellow 代码 代码 4 创建创建 choice 添加添加 itemGreen 代码 代码 5 将当前窗口注册为将当前窗口注册为 choice 的的 ItemEvent 事件监视器事件监视器 add choice BorderLayout NORTH try Class cs Class forName SignalCanvas signal SignalCanvas cs newInstance add signal BorderLayout CENTER catch Exception e add new Label 您还没有编写您还没有编写SignalCanvas类类 BorderLayout CENTER setBounds 100 100 360 300 setVisible true validate addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 16 public void itemStateChanged ItemEvent e String item 代码 代码 6 choice 返回被选中的条目返回被选中的条目 int w signal getBounds width int h signal getBounds height int m Math min w h signal setRadius m 6 if item equals itemRed if signal null signal setRed 1 signal setYellow 0 signal setGreen 0 signal setPosition w 3 0 signal repaint else if item equals itemYellow if signal null signal setRed 0 signal setYellow 1 signal setGreen 0 signal setPosition w 3 h 3 signal repaint else if item equals itemGreen if signal null signal setRed 0 signal setYellow 0 signal setGreen 1 signal setPosition w 3 2 h 3 signal repaint 文件名 文件名 SignalMainClass java public class SignalMainClass public static void main String args SignalFrame frame frame new SignalFrame 17 frame setTitle 信号灯信号灯 实验实验 3 布局与日历布局与日历 本程序运行后界面 能否改为 Windows 的日期和时间日历 1 答案 答案 代码 代码 1 pCenter setLayout new GridLayout 7 7 代码 代码 2 pCenter add titleName i 代码 代码 3 pCenter add labelDay i 代码 代码 4 add scrollPane BorderLayout CENTER 代码 代码 5 add pNorth BorderLayout NORTH 代码 代码 6 add pSouth BorderLayout SOUTH 2 模板代码 模板代码 文件名 文件名 CalendarBean java import java util Calendar public class CalendarBean String day int year 2005 month 0 public void setYear int year this year year 18 public int getYear return year public void setMonth int month this month month public int getMonth return month public String getCalendar String a new String 42 Calendar 日历日历 Calendar getInstance 日历日历 set year month 1 1 int 星期几星期几 日历日历 get Calendar DAY OF WEEK 1 int day 0 if month 1 month 3 month 5 month 7 month 8 month 10 month 12 day 31 if month 4 month 6 month 9 month 11 day 30 if month 2 if year 4 0 else day 28 for int i 星期几星期几 n 1 i 星期几星期几 day i a i String valueOf n n return a 文件名 文件名 CalendarFrame java import java util import java awt import java awt event import java applet 19 public class CalendarFrame extends Frame implements ActionListener Label labelDay new Label 42 Button titleName new Button 7 String name 日日 一一 二二 三三 四四 五五 六六 Button nextMonth previousMonth int year 2006 month 10 CalendarBean calendar Label showMessage new Label Label CENTER public CalendarFrame Panel pCenter new Panel 代码 代码 1 将将 pCenter 的布局设置为的布局设置为 7 行行 7 列的列的 GridLayout 布局 布局 for int i 0 i 7 i titleName i new Button name i 代码 代码 2 pCenter 添加组件添加组件 titleName i for int i 0 i 42 i labelDay i new Label Label CENTER 代码 代码 3 pCenter 添加组件添加组件 labelDay i calendar new CalendarBean calendar setYear year calendar setMonth month String day calendar getCalendar for int i 0 i12 month 1 calendar setMonth month String day calendar getCalendar for int i 0 i 42 i labelDay i setText day i else if e getSource previousMonth month month 1 if month 1 month 12 calendar setMonth month String day calendar getCalendar for int i 0 i 0 root1 b Math sqrt disk 2 a else throw new NoRealRootException 没有实根没有实根 else throw new NoRealRootException 不是二次方程不是二次方程 return root1 22 public double getRootTwo throws NoRealRootException NoSquareEquationException if a 0 double disk b b 4 a c if disk 0 root2 b Math sqrt disk 2 a else throw new NoRealRootException 没有实根没有实根 else throw new NoRealRootException 不是二次方程不是二次方程 return root2 class NoRealRootException extends Exception String message NoRealRootException String s message s public String getMessage return message class NoSquareEquationException extends Exception String message NoSquareEquationException String s message s public String getMessage return message 文件名 文件名 EquationFrame java import java awt import java awt event public class EquationFrame extends Frame implements ActionListener SquareEquation equation TextField textA textB textC TextArea showRoots Button controlButton 23 public EquationFrame equation new SquareEquation textA new TextField 8 textB new TextField 8 textC new TextField 8 showRoots new TextArea controlButton new Button 确定确定 Panel pNorth new Panel pNorth add new Label 二次项系数二次项系数 pNorth add textA pNorth add new Label 一次项系数一次项系数 pNorth add textB pNorth add new Label 常数项系数常数项系数 pNorth add textC pNorth add controlButton 代码 代码 1 当前窗口作为当前窗口作为 controlButton 的的 ActionEvent 事件的监视器事件的监视器 add pNorth BorderLayout NORTH add showRoots BorderLayout CENTER setBounds 100 100 630 160 setVisible true validate addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 public void actionPerformed ActionEvent e try double a Double parseDouble 代码 代码 2 textA 调用方法获取其中调用方法获取其中 的文本的文本 double b Double parseDouble 代码 代码 3 textB 调用方法获取其中调用方法获取其中 的文本的文本 double c Double parseDouble 代码 代码 4 textC 调用方法获取调用方法获取 其中的文本其中的文本 equation setA a equation setB b equation setC c textA setText a textB setText b textC setText c showRoots append n 根 根 equation getRootOne showRoots append 根 根 equation getRootTwo 24 catch Exception ex showRoots append n ex n 文件名 文件名 EquationMainClass java public class EquationMainClass public static void main String args EquationFrame frame new EquationFrame 实验实验 2 字体对话框字体对话框 1 答案 答案 代码 代码 1 setModal true 代码 代码 2 setVisible false 代码 代码 3 setVisible false 代码 代码 4 new FontDialog this 代码 代码 5 setVisible true 代码 代码 6 dialog setTitle 字体对话框字体对话框 2 模板代码 模板代码 文件名 文件名 FontFamilyNames java import java awt GraphicsEnvironment public class FontFamilyNames String fontName public String getFontName GraphicsEnvironment ge GraphicsEnvironment getLocalGraphicsEnvironment fontName ge getAvailableFontFamilyNames return fontName 文件名 文件名 FontDialog java import java awt event import java awt import javax swing JLabel public class FontDialog extends Dialog implements ItemListener ActionListener FontFamilyNames fontFamilyNames int fontSize 38 String fontName 25 Choice fontNameList JLabel label Font font Button yes cancel static int YES 1 NO 0 int state 1 FontDialog Frame f super f fontFamilyNames new FontFamilyNames 代码 代码 1 对话框设置为有模式对话框设置为有模式 yes new Button Yes cancel new Button cancel yes addActionListener this cancel addActionListener this label new JLabel hello 奥运奥运 JLabel CENTER fontNameList new Choice String name fontFamilyNames getFontName for int k 0 k name length k fontNameList add name k fontNameList addItemListener this add fontNameList BorderLayout NORTH add label BorderLayout CENTER Panel pSouth new Panel pSouth add yes pSouth add cancel add pSouth BorderLayout SOUTH setBounds 100 100 280 170 addWindowListener new WindowAdapter public void windowClosing WindowEvent e state NO setVisible false validate public void itemStateChanged ItemEvent e fontName String fontNameList getSelectedItem font

温馨提示

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

评论

0/150

提交评论