JAVA实验6答案教学教材
- 格式:doc
- 大小:62.00 KB
- 文档页数:8
Java语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
第Ⅰ部分:实验指导实验1:Java开发环境J2SE一、实验目的(1)学习从网络上下载并安装J2SE开发工具。
(2)学习编写简单的Java Application程序.(3)了解Java源代码、字节码文件,掌握Java程序的编辑、编译和运行过程。
二、实验任务从网络上下载或从CD-ROM直接安装J2SE开发工具,编写简单的Java Application程序,编译并运行这个程序。
三、实验内容1.安装J2SE开发工具Sun公司为所有的java程序员提供了一套免费的java开发和运行环境,取名为Java 2 SDK,可以从上进行下载。
安装的时候可以选择安装到任意的硬盘驱动器上,例如安装到C:\j2sdk1.4.1_03目录下。
教师通过大屏幕演示J2SE的安装过程,以及在Windows98/2000/2003下环境变量的设置方法。
2.安装J2SE源代码编辑工具Edit Plus教师通过大屏幕演示Edit Plus的安装过程,以及在Windows98/2000/2003操作系统环境下编辑Java 原程序的常用命令的用法。
3.编写并编译、运行一个Java Application程序。
创建一个名为HelloWorldApp的java Application程序,在屏幕上简单的显示一句话"老师,你好!"。
public class HelloWorldApp{public static void main(String[] args){System.out.println("老师,你好!");}}4.编译并运行下面的Java Application程序,写出运行结果。
1:public class MyClass {2:private int day;3:private int month;4:private int year;5:public MyClass() {6:day = 1;7:month = 1;8:year = 1900;9:}10:public MyClass(int d,int m,int y) {11:day = d;12:month = m;13:year = y;14:}15:public void display(){16:System.out.println(day + "-" + month + "-" + year);17:}18:public static void main(String args[ ]) {19:MyClass m1 = new MyClass();20:MyClass m2 = new MyClass(25,12,2001);21:m1.display();22:m2.display();23:}24:}运行结果:1-1-190025-12-2001实验2:Java基本数据类型一、实验目的(1)掌握javadoc文档化工具的使用方法。
Java程序设计实验指导书(答案) Java程序设计实验指导书(答案)第一章:概述Java程序设计实验是计算机相关专业学生在学习Java程序设计课程过程中的重要环节。
该实验指导书的编写旨在帮助学生掌握Java编程的基本技能和方法,提升他们的实践能力和创新思维。
本章将介绍实验指导书的目的、使用方法以及注意事项。
第二章:实验环境搭建2.1 JDK安装首先,学生需要在自己的计算机上安装Java开发工具包(JDK)。
具体安装步骤如下:(这里给出详细的步骤说明,包括下载JDK安装包、运行安装程序等)2.2 IDE选择在实验中,我们推荐学生使用Eclipse作为Java开发环境。
下面是Eclipse的安装步骤:(这里也给出详细的步骤说明,包括下载Eclipse安装包、运行安装程序等)2.3 实验文件结构为了方便实验的进行和管理,学生需要按照一定的文件结构组织他们的项目代码和资源文件。
以下是一个示例的实验文件结构:(这里列举一个具体的示例,包括主目录、子目录和文件等)第三章:实验内容第一次实验内容:Hello World程序3.1 实验目的本次实验旨在让学生熟悉Java程序的基本结构和编写过程,以及编译和运行Java程序的方法。
3.2 实验要求学生需要按照以下要求编写一个简单的Hello World程序:(这里给出具体的编码要求,并提醒学生注意细节和常见错误)3.3 实验步骤学生可以按照以下步骤进行实验:(这里给出详细的实验步骤,包括创建项目、编写代码、编译运行等)第二次实验内容:变量和数据类型3.1 实验目的本次实验旨在让学生理解和掌握Java中的变量声明、赋值和数据类型的使用方法,以及常见数据类型的特点。
3.2 实验要求学生需要完成以下任务:(这里列出具体的任务要求,包括变量的声明和初始化、数据类型的使用等)3.3 实验步骤学生可以按照以下步骤进行实验:(这里给出详细的实验步骤,包括创建新的Java类、编写代码、编译运行等)第四章:实验总结本章将对前两次实验进行总结,并提出对学生的建议和指导。
第6章习题解答1.简述Java中设计图形用户界面程序的主要步骤。
对于设计图形用户界面程序而言,一般分为两个步骤:第一步,设计相应的用户界面,并根据需要对相关的组件进行布局;第二步,添加相关的事件处理,如鼠标、菜单、按钮和键盘等事件。
2.试说明容器与组件之间的关系。
组件(component)是图形用户界面中的各种部件(如标签、按钮、文本框等等),所有的组件类都继承自JComponent类。
容器(container)是用来放置其他组件的一种特殊部件,在java中容器用Container类描述。
3.阅读下面程序,说明其运行结果和功能。
//filename:MyFrame.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class MyFrame{public static void main(String agrs[]){JFrame f=new JFrame("简单窗体示例");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JLabel l=new JLabel("习题1");f.getContentPane().add(l,BorderLayout.CENTER);f.pack();f.setVisible(true);}}程序的运行结果如下:4.阅读下面程序,说明其运行结果和功能。
//filename:TestButton.javaimport java.awt.*;import javax.swing.*;public class TestButton extends JFrame{JButton b1,b2;TestButton(String s){super(s);b1=new JButton("按钮1");b2=new JButton("按钮2");setLayout(new FlowLayout());add(b1);add(b2);setSize(300,100);setVisible(true);}public static void main(String args[]){ TestButton test;test=new TestButton("测试按钮"); }}程序的运行结果如下:5.阅读下面程序,说明其运行结果和功能。
广东海洋大学学生实验报告书(学生用表)实验名称实验六. Java的接口与实现课程名称Java程序设计与开发技术课程号16232204学院(系) 信息学院专业计算机科学与技术班级计科学生姓名学号实验地点钟海楼04019实验日期2015年10月26日一、实验目的(1)学习掌握Java中类怎样实现接口、接口回调技术;(2)学习掌握Java 程序中面向接口的编程思想。
二、实验任务完成实验六指导上实验1、实验2、实验3的实验任务。
三、实验仪器设备和材料安装有J2SE开发工具的PC机。
四、实验内容和步骤实验1代码如下:Estimator.javainterface CompurerAverage{public double average(double x[]);}class Gymnastics implements CompurerAverage{public double average(double x[]){int count=x.length;double aver=0,temp=0;for(int i=0;i<count;i++){for(int j=i;j<count;j++){if(x[j]<x[i]){temp=x[j];x[j]=x[i];x[i]=temp;}}}for(int i=1;i<count-1;i++){GDOU-B-11-112aver=aver+x[i];}if(count>2)aver=aver/(count-2);elseaver=0;return aver;}}class School implements CompurerAverage{public double average(double[] x){int count=x.length;double sum=0;for(int i=0;i<count;i++){sum+=x[i];}return sum/count;}}public class Estimator{public static void main(String[] args){double a[]={9.89,9.88,9.99,9.12,9.69,9.76,8.97};double b[]={89,56,78,90,100,77,56,45,36,79,98};CompurerAverage computer;computer=new Gymnastics();double result=computer.average(a);System.out.printf("%n");System.out.printf("体操选手最后得分:%5.3f\n",result);computer=new School();result=computer.average(b);System.out.printf("班级考试平均分数:%-5.2f\n",result);}}运行结果:---------- JAVAC ----------Estimator.java:27: 错误: School不是抽象的, 并且未覆盖CompurerAverage中的抽象方法average(double[])class School implements CompurerAverage{^1 个错误实验2代码如下:CheckCarWeight.javainterface ComputerWeight{public double computerWeight();}class Television implements ComputerWeight{public double computerWeight(){return 10.0;}}class Computer implements ComputerWeight{public double computerWeight(){return 8.0;}}class WashMachine implements ComputerWeight{public double computerWeight(){return 35.5;}}class Truck{ComputerWeight[] goods;double totalWeihts=0;Truck(ComputerWeight[] goods){this.goods=goods;}public void setGoods(ComputerWeight[] goods){this.goods=goods;}public double getTotalWeigths(){totalWeihts=0;for(int i=0;i<goods.length;i++){totalWeihts+=goods[i].computerWeight();}return totalWeihts;}public class CheckCarWeight{public static void main(String[] args){ComputerWeight[] goods=new ComputerWeight[650];for(int i=0;i<goods.length;i++){if(i%3==0)goods[i]=new Television();if(i%3==1)goods[i]=new Computer();if(i%3==2)goods[i]=new WashMachine();}Truck truck=new Truck(goods);System.out.printf("\n货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeigths());goods=new ComputerWeight[68];for(int i=0;i<goods.length;i++){if(i%2==0)goods[i]=new Television();elsegoods[i]=new WashMachine();}truck.setGoods(goods);System.out.printf("货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeigths());}}运行结果:练习:class Refrigerrator implements ComputerWeight{public double computerWeight(){return 10.5;}}不需修改Truck类实验3代码如下:CheckDogState.javainterface DogState{public void showState();}class SoftlyState implements DogState{public void showState(){System.out.println("听主人的命令");}}class MeetEnemyState implements DogState{public void showState(){System.out.println("狂叫,并冲向去狠咬敌人");}}class MeetFriendState implements DogState{public void showState(){System.out.println("晃动尾巴,表示欢迎");}}class MeetAnotherDog implements DogState{public void showState(){System.out.println("嬉戏");}}class Dog{DogState state;public void show(){state.showState();}public void setState(DogState s){state=s;}}public class CheckDogState{public static void main(String[] args){Dog yellowDog=new Dog();System.out.print("狗在主人面前:");yellowDog.setState(new SoftlyState());yellowDog.show();System.out.print("狗遇到敌人:");yellowDog.setState(new MeetEnemyState());yellowDog.show();System.out.print("狗遇到朋友:");yellowDog.setState(new MeetFriendState());yellowDog.show();System.out.print("狗遇到同伴:");yellowDog.setState(new MeetAnotherDog());yellowDog.show();}}运行结果:练习:CheckWaterState.javainterface WaterState{public void showState();}class ColdState implements WaterState{public void showState(){System.out.println("固态");}}class OrdinaryState implements WaterState{ public void showState(){System.out.println("液态");}}class HotState implements WaterState{public void showState(){System.out.println("气态");}}class Water{WaterState state;public void show(){state.showState();}public void setState(WaterState s){state=s;}}public class CheckWaterState{public static void main(String[] args){Water water=new Water();System.out.print("低于0°C:");water.setState(new ColdState());water.show();System.out.print("高于0°C且低于100°C:");water.setState(new OrdinaryState());water.show();System.out.print("高于100°C:");water.setState(new HotState());water.show();}}成绩指导教师孙兵日期2015年10月30日注:请用A4纸书写,不够另附纸。
pp2.3public class fudian {public static void main(String[] args) {float a=2.10f,b=3.70f;float Result1,Result2,Result3;Result1=a+b;Result2=a-b;Result3=a*b;System.out.println("Result1 is:"+Result1);System.out.println("Result2 is:"+Result2);System.out.println("Result3 is:"+Result3);}}2.4public class TempConverter {public static void main(String[] args) {final int BASE = 32;final double CONVERSION_FACTOR = 5.0 / 9.0;double celsiusTemp;int fahrenheitTemp = 70; // value to convertcelsiusTemp = (fahrenheitTemp - BASE)*CONVERSION_FACTOR;System.out.println ("Fahrenheit Equivalent: " + fahrenheitTemp);System.out.println ("Celsius Temperature: " + celsiusTemp);}}2.5public class yinglizhuanqianmi {public static void main(String[] args) {float Base=1.60935f;float Qianmi;float Yingli=19.85f;Qianmi=Yingli*Base;System.out.println ("Ying Li: " + Yingli);System.out.println ("Qian Mi: " +Qianmi);}}2.6public class TimeConverter1 {public static void main(String[] args) {int Hour=5,Minute=35,Second=51;int SECONDS;SECONDS=Hour*60*60+Minute*60+Second;System.out.println (+Hour+"时"+Minute+"分"+Second+"秒");System.out.println ("换算成秒: " + SECONDS);}}2.7public class TimeConverter2 {public static void main(String[] args) {int SECONDS=10853;int Hour,Minute,Second;Second=SECONDS%60;Minute=(SECONDS-Second)%60;Hour=(SECONDS-Second-Minute*60)/3600;System.out.println (SECONDS+"秒,转化为");System.out.println (Hour+"时"+Minute+"分"+Second+"秒");}}2.9import java.util.*;public class Dollarbill {public static void main(String[] args) {float Dollar1,Dollar2;int Ten,Five,One,Quarters,Dimes,Nickles,Pennies;Scanner reader=new Scanner(System.in);System.out.println("输入币值:");Dollar1=reader.nextFloat();Dollar2=Dollar1*100;Pennies= (int)Dollar2%5;Nickles=((int)Dollar2%10-Pennies)/5;Dimes=((int)Dollar2-Pennies-Nickles*5)%50/10;Quarters=(int)Dollar2%100/50;One=((int)Dollar2- Pennies-Nickles*5-Dimes*10-Quarters*50)%500/100;Five=(int)Dollar2%1000/500;Ten=(int)Dollar2/1000;System.out.println(Ten+ "ten dollar bills");System.out.println(Five+ " five dollar bills");System.out.println(One+ "one dollar bills");System.out.println(Quarters+ "quarters dollar bills");System.out.println(Dimes+ "dimes dollar bills");System.out.println(Nickles+ "nickles dollar bills");System.out.println(Pennies+ "pennies dollar bills!");}}2.11import java.util.*;public class Fenshuzhuanhuan {public static void main(String[] args) {int x,y;double Result=0;Scanner reader=new Scanner(System.in);System.out.println("输入x:");x=reader.nextInt();System.out.println("输入y:");y=reader.nextInt();Result+=x/y;System.out.println ("分数"+x+"/"+y);System.out.println ("转换成小数是: " + Result);}}2.16import javax.swing.JApplet;import java.awt.*;public class Olympiclogo extends JApplet{public void paint (Graphics page) {page.setColor(Color.blue);page.drawOval(25, 65, 40, 40);page.setColor(Color.yellow);page.drawOval (55, 65, 40, 40);page.setColor(Color.black);page.drawOval (85, 65, 40, 40);page.setColor(Color.green);page.drawOval (115, 65, 40, 40);page.setColor(Color.red);page.drawOval (145, 65, 40, 40);// circlepage.setColor(Color.cyan);page.drawString ("OL YMPIC LOGO", 40, 30);}}2.19import java.applet.*;import java.awt.*;public class Ex2_19 extends Applet{public void paint (Graphics page){page.setColor(Color.BLACK);page.setFont(new Font("楷体",Font.ITALIC+Font.BOLD,30));page.drawString ("林少锋", 40, 30);page.setColor(Color.blue);page.setFont(new Font("宋体",Font.BOLD,30));page.drawString ("林少锋", 70, 80);}}2.20import java.applet.*;import java.awt.*;public class Ex2_20 extends Applet{public void paint (Graphics page){page.drawOval(35, 35, 130, 130);page.setColor(Color.red);page.fillArc(35, 35, 130, 130,0,45);page.setColor(Color.blue);page.fillArc(35, 35, 130, 130,45,45);page.setColor(Color.yellow);page.fillArc(35, 35, 130, 130,90,45);page.setColor(Color.cyan);page.fillArc(35, 35, 130, 130,135,45);page.setColor(Color.gray);page.fillArc(35, 35, 130, 130,180,45);page.setColor(Color.green);page.fillArc(35, 35, 130, 130,225,45);page.setColor(Color.darkGray);page.fillArc(35, 35, 130, 130,270,45);page.setColor(Color.pink);page.fillArc(35, 35, 130, 130,315,45);}}PP4.1方法1import java.util.*;public class CreateSphere {/*** @param args*/public static void main(String[] args) {// TODO 自动生成方法存根System.out.println("请输入直径d:");Scanner scan=new Scanner(System.in);double d=scan.nextDouble();Sphere D=new Sphere(d);D.Square();D.Volum();System.out.println(D.toString());}}public class Sphere {final double PI=3.14;double V,S;double d;Sphere(double d){this.d=d;}public void V olum(){V=(4/3)*PI*(d/2)*(d/2)*(d/2);}public void Square(){S=4*PI*(d/2)*(d/2);}public String toString(){String s="";String result1=Double.toString(S);String result2=Double.toString(V);s=("体积为:"+result2+"面积为:"+result1);return s;}}方法2//Sphere.javapublic class Sphere{private double diameter;public Sphere(){//构造方法:无参数this.diameter = 1.0;}public Sphere(double d){ //构造方法:带一个参数this.diameter = d;}public void setDiameter(double d) {//设置直径值的方法this.diameter = d;}public double getDiameter(){//获取直径值的方法return this.diameter;}public double volume(){//计算球的体积return 4*Math.PI*Math.pow(this.diameter/2,3)/3;}public double area(){//计算球的表面积return 4*Math.PI*Math.pow(this.diameter/2,2);}public String toString(){String out = "该球体的直径为:" + this.diameter + "\n" + "该球体的表面积为:" + this.area() + "\n" +"该球体的体积为:" + this. volume();return out;}}//MultiSphere.javaimport java.util.Scanner;public class MultiSphere{public static void main(String[] args){Scanner scan = new Scanner(System.in);Sphere sphere1 = new Sphere();Sphere sphere2 = new Sphere(3.5);System.out.println("sphere1: " + sphere1 + "\n");System.out.println("sphere2: " + sphere2 + "\n");System.out.println("sphere1和sphere2分别调用无参构造方法" +"和带一个参数的构造方法进行初始化。
AnjoyoJava06课后习题一、选择题:1.下面关于异常的说法正确的一项是()。
A、异常就是在程序的运行过程中所发生的不正常的事件,但它不会中断正在运行的程序。
B、Error类和Exception类都是Throwable类的子类。
C、Exception处理的是Java运行环境中的内部错误或者硬件问题,比如,内存资源不足、系统崩溃等。
D、Error处理的是因为程序设计的瑕疵而引起的问题或者外在的输入等引起的一般性问题,例如:在开平方的方法中输入了一个负数,对一个为空的对象进行操作以及网络不稳定引起的读取网络问题等。
2.引起RuntimeException异常的原因不包括下面哪一项()。
A、错误的类型转换B、试图从文件结尾处读取信息C、试图访问一个空对象D、数组越界访问3.引起IOException异常的原因不包括下面哪一项()。
A、试图从文件结尾处读取信息B、试图打开一个不存在或者格式错误的URL。
C、数学计算错误D、用Class.forName()来初始化一个类的时候,字符串参数对应的类不存在。
4.下面哪一项不是RuntimeException异常中的一类()。
A、ClassNotFoundException:无法找到需要的类文件异常B、NumberFormatException:数字转化格式异常C、IllgalArgumentException:非法参数值异常D、IllegalStateException:对象状态异常,如对未初始化的对象调用方法5.IOException异常不包括下面哪一项()。
A、EOFException:读写文件尾异常B、InterruptedException:线程中断C、SocketException:Socket通信异常D、MalformedURLException:URL格式错误异常6.下列关于try-catch-finally处理异常描述有误的一项是()。
A、异常处理可以定义在方法体、自由块或构造方法中。
J A V A实验6答案广东海洋大学学生实验报告书(学生用表)实验名称实验六. Java的接口与实现课程名称Java程序设计与开发技术课程号16232204学院(系) 信息学院专业计算机科学与技术班级计科学生姓名学号实验地点钟海楼04019实验日期2015年10月26日一、实验目的(1)学习掌握Java中类怎样实现接口、接口回调技术;(2)学习掌握Java 程序中面向接口的编程思想。
二、实验任务完成实验六指导上实验1、实验2、实验3的实验任务。
三、实验仪器设备和材料安装有J2SE开发工具的PC机。
四、实验内容和步骤实验1代码如下:Estimator.javainterface CompurerAverage{public double average(double x[]);}class Gymnastics implements CompurerAverage{public double average(double x[]){int count=x.length;double aver=0,temp=0;for(int i=0;i<count;i++){for(int j=i;j<count;j++){if(x[j]<x[i]){temp=x[j];x[j]=x[i];x[i]=temp;}}}GDOU-B-11-112for(int i=1;i<count-1;i++){aver=aver+x[i];}if(count>2)aver=aver/(count-2);elseaver=0;return aver;}}class School implements CompurerAverage{public double average(double[] x){int count=x.length;double sum=0;for(int i=0;i<count;i++){sum+=x[i];}return sum/count;}}public class Estimator{public static void main(String[] args){double a[]={9.89,9.88,9.99,9.12,9.69,9.76,8.97};double b[]={89,56,78,90,100,77,56,45,36,79,98};CompurerAverage computer;computer=new Gymnastics();double result=computer.average(a);System.out.printf("%n");System.out.printf("体操选手最后得分:%5.3f\n",result);computer=new School();result=computer.average(b);System.out.printf("班级考试平均分数:%-5.2f\n",result);}}运行结果:---------- JAVAC ----------Estimator.java:27: 错误: School不是抽象的, 并且未覆盖CompurerAverage中的抽象方法average(double[])class School implements CompurerAverage{^1 个错误实验2代码如下:CheckCarWeight.javainterface ComputerWeight{public double computerWeight();}class Television implements ComputerWeight{public double computerWeight(){return 10.0;}}class Computer implements ComputerWeight{public double computerWeight(){return 8.0;}}class WashMachine implements ComputerWeight{public double computerWeight(){return 35.5;}}class Truck{ComputerWeight[] goods;double totalWeihts=0;Truck(ComputerWeight[] goods){this.goods=goods;}public void setGoods(ComputerWeight[] goods){this.goods=goods;}public double getTotalWeigths(){totalWeihts=0;for(int i=0;i<goods.length;i++){totalWeihts+=goods[i].computerWeight();}return totalWeihts;}public class CheckCarWeight{public static void main(String[] args){ComputerWeight[] goods=new ComputerWeight[650];for(int i=0;i<goods.length;i++){if(i%3==0)goods[i]=new Television();if(i%3==1)goods[i]=new Computer();if(i%3==2)goods[i]=new WashMachine();}Truck truck=new Truck(goods);System.out.printf("\n货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeigths());goods=new ComputerWeight[68];for(int i=0;i<goods.length;i++){if(i%2==0)goods[i]=new Television();elsegoods[i]=new WashMachine();}truck.setGoods(goods);System.out.printf("货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeigths());}}运行结果:练习:class Refrigerrator implements ComputerWeight{public double computerWeight(){return 10.5;}}不需修改Truck类实验3代码如下:CheckDogState.javainterface DogState{public void showState();}class SoftlyState implements DogState{public void showState(){System.out.println("听主人的命令");}}class MeetEnemyState implements DogState{public void showState(){System.out.println("狂叫,并冲向去狠咬敌人");}}class MeetFriendState implements DogState{public void showState(){System.out.println("晃动尾巴,表示欢迎");}}class MeetAnotherDog implements DogState{public void showState(){System.out.println("嬉戏");}}class Dog{DogState state;public void show(){state.showState();}public void setState(DogState s){state=s;}}public class CheckDogState{public static void main(String[] args){Dog yellowDog=new Dog();System.out.print("狗在主人面前:");yellowDog.setState(new SoftlyState());yellowDog.show();System.out.print("狗遇到敌人:");yellowDog.setState(new MeetEnemyState());yellowDog.show();System.out.print("狗遇到朋友:");yellowDog.setState(new MeetFriendState());yellowDog.show();System.out.print("狗遇到同伴:");yellowDog.setState(new MeetAnotherDog());yellowDog.show();}}运行结果:练习:CheckWaterState.javainterface WaterState{public void showState();}class ColdState implements WaterState{public void showState(){System.out.println("固态");}}class OrdinaryState implements WaterState{public void showState(){System.out.println("液态");}}class HotState implements WaterState{public void showState(){System.out.println("气态");}}class Water{WaterState state;public void show(){state.showState();}public void setState(WaterState s){state=s;}}public class CheckWaterState{public static void main(String[] args){Water water=new Water();System.out.print("低于0°C:");water.setState(new ColdState());water.show();System.out.print("高于0°C且低于100°C:");water.setState(new OrdinaryState());water.show();System.out.print("高于100°C:");water.setState(new HotState());water.show();}}成绩指导教师孙兵日期2015年10月30日注:请用A4纸书写,不够另附纸。