作者:保佑麻木_711 | 来源:互联网 | 2023-02-05 09:46
自己的一个练习的小尝试,感觉很有意思,第一次自己打出来的小程序1.定义一个canattack()接口,其中有一个attack()抽象方法2.定义一个canmove()接口,其中有一个move()抽象方
自己的一个练习的小尝试,感觉很有意思,第一次自己打出来的小程序
1.定义一个canattack()接口,其中有一个attack()抽象方法
2.定义一个canmove()接口,其中有一个move()抽象方法
3.定义一个抽象类Weapon(),实现canattack()和canmove()两个接口,但不实现其中的抽象方法。
4.定义三个类,Tank,Fly,Ship,都继承Weapon分别用不同的方式实现 Weapon 类中的抽象方法
5.写一个类Army,代表一支军队,这个类有一个属性是Weapon数组w(用来存储该军队所拥有的所有武器)该类还
提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量,并用这一大小
来初始化数组w。该类还提供一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。在这
个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动
6.定义一个主类来实现这些步骤。
package 尝试;
import java.util.Scanner;
interface Canattack{//定义Canattack接口
void attack();
}
interface Canmove{//定义Canmove接口
void move();
}
abstract class Weapon implements Canattack,Canmove{//定义Weapon抽象类实现两个接口
public void attack(){}
public void move(){}
}
class Tank extends Weapon{//不同的类实现不同的方法
public void attack(){
System.out.println("tank攻击!");
}
public void move(){
System.out.println("tank移动!");
}
}
class Fly extends Weapon{
public void attack(){
System.out.println("fly攻击!");
}
public void move(){
System.out.println("fly移动!");
}
}
class Ship extends Weapon{
public void attack(){
System.out.println("ship攻击!");
}
public void move(){
System.out.println("ship移动!");
}
}
class Army{//定义Army类
int j=0;
int n;
Weapon[] w;//定义Weapon数组
public int getMax() {
return n;
}
public void setMax(int n){
this.n = n;
}
public Army(int n)
{
this.n = n;
w = new Weapon[n];
System.out.println("您最多拥有"+n+"个武器!!!");
}
public void addWeapon(Weapon wa){
if(j System.out.println("武器库足够!"+"已增加"+(j+1)+"个武器");
w[j]=wa;
j++; }
else{
System.out.println("警告:武器库已满!!!不能增加武器!!!");
}
}
public void attackAll(){//全军出击
System.out.println();
System.out.println("所有武器准备战斗!!!");
for(int i=0;i System.out.print((i+1)+"号");
w[i].attack();
}
}
public void moveAll(){//三军前进
System.out.println();
System.out.println("所有武器准备移动!!!");
for(int i=0;iSystem.out.print((i+1)+"号");
w[i].move();
}
}
}
class father {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("请输入武器库容量");
int n = s.nextInt();
Army a = new Army(n);
System.out.println("输入yes添加武器,输入其他则不录入");
String m = s.next();//添加武器
while(m.equals("yes"))
{
System.out.println("1.Tank 2.Fly 3.Ship");
System.out.println("请选择:");
int l=s.nextInt();//请选择武器种类
if(l==1)
{
a.addWeapon(new Tank());
}
else if(l==2)
{
a.addWeapon(new Fly());
}
else if(l==3)
{
a.addWeapon(new Ship());
}
else{
System.out.println("输入错误");
}
System.out.println("输入yes添加武器,输入其他则退出");
m = s.next();
}
a.moveAll();
a.attackAll();
}
}