预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

亲,该文档总共13页,到这已经超出免费预览范围,如果喜欢就直接下载吧~

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

实验报告 实验课程:Java面向程序设计实验 实验内容:类与对象 院(系):计算机学院 专业:计算机科学与技术(软件工程方向) 班级: 学生姓名: 学号: 指导教师: 2014年3月26日 一、实验目的: 1、掌握用类来封装对象的属性和行为的方法; 2、掌握对象的组合和参数传递; 3、掌握类变量与实例变量、类方法与实例方法的区别。 二、实验内容 (-)实验题目一:编写一个java应用程序,该程序中有两个类:Tank和Fight具体要求如下: 1、Tank类有一个double类型变量speed,用于刻画坦克的速度;一个int型变量bulletAmount,用于刻画坦克的炮弹数量。定义了speedUp()和speedDown()方法,体现坦克有加速、减速行为;定义了setBulletAmount(intp)方法,用于设置坦克炮弹的数量;定义了fire()方法,体现坦克有开炮行为。 程序源代码: packagep1; publicclassTank{ doublespeed; intbulletAmount; voidspeedUp(ints){ speed=s+speed; } voidspeedDown(intd){ if(speed-d>=0) speed=speed-d; else speed=0; } voidsetBulletAmount(intm){ bulletAmount=m; } intgetBulletAmount(){ returnbulletAmount; } doublegetSpeed(){ returnspeed; } voidfire(){ if(bulletAmount>=1){ bulletAmount=bulletAmount-1; System.out.println("打出一发炮弹"); } else{ System.out.println("没有炮弹了,无法开火"); } } } packagep1; publicclassFight{ publicstaticvoidmain(Stringargs[]){ Tanktank1,tank2; tank1=newTank(); tank2=newTank(); tank1.setBulletAmount(10); tank2.setBulletAmount(10); System.out.println("tank1的炮弹数量:"+tank1.getBulletAmount()); System.out.println("tank2的炮弹数量:"+tank2.getBulletAmount()); tank1.speedUp(80); tank2.speedUp(90); System.out.println("tank1目前的速度:"+tank1.getSpeed()); System.out.println("tank2目前的速度:"+tank2.getSpeed()); tank1.speedDown(15); tank2.speedDown(30); System.out.println("tank1目前的速度:"+tank1.getSpeed()); System.out.println("tank2目前的速度:"+tank2.getSpeed()); System.out.println("tank1开火:"); tank1.fire(); System.out.println("tank2开火:"); tank2.fire(); tank2.fire(); System.out.println("tank1的炮弹数量:"+tank1.getBulletAmount()); System.out.println("tank2的炮弹数量:"+tank2.getBulletAmount()); } } 实验结果: 图1 3、实验课后练习: (1)改进speedUp方法,使得Tank类的对象调用它能将Speed值超过220; 答:只需加入如下代码,其实验结果如图2: voidspeedUp(ints){ if(s+speed<=200)//加入判断语句即可 speed=s+speed; } 图2:tank2加速200,超过220,所以tank2数值保持不变 (2)增加一个刹车方法:voidbrake(),Tank类的对象调用它将speed的值变为0. 答:只需增加如下代码:其结果如图3所示: voidbrake(){ speed=0;