任务十一 异常和容器类(提交源代码和运行结果)
5
刘兴梅
开始于 2018-05-07 16:07
0 16 41
已截止

任务尚未发布或者你没有权限查看任务内容。

任务讨论
刘兴梅

非常好。

老师,我重新改了改这个代码 package eleven;

public class Ball {
	private int id;
	private String type;
	public Ball() {
		this.id=1;
		this.type="M54";
	}
	public Ball(int id,String type)
	{
		this.id=id;
		this.type=type;
	}
	public int getId() {
		return id;
	}
	public String getType()
	{
		return type;
	}
	public void print() {
		
	System.out.println("型号编号"+this.id+"-"+this.type);
	}
}

package eleven;

import java.util.ArrayList;
import java.util.List;

public class Gun {
	private int id;
	private String type;
	private List<Ball> danjia;
	//private List<Ball> chudan;
	//弹夹
	private int num;//装弹数量
	public Gun()
	{
		this.id=1;
		this.type="M54";
		this.num=6;
		this.danjia=new ArrayList<>(num);
		
	}
	public Gun(int id,String type,int num)
	{
		this.id=id;
		this.type=type;
		this.danjia=new ArrayList<>(num);
		
	}
	public void load(Ball a) throws Exception
	{
		if(danjia.size()==this.num)
		{
			throw new Exception("弹夹已满");
		}
		else
		{
			danjia.add(a);
		}
	}
	
	public Ball shooting() throws Exception
	{
		if(danjia.isEmpty())
		{
			throw new Exception("弹夹为空");
			
		}
		else {
			return  danjia.remove(0);
		
		}
	}
	//获取当前弹夹内子弹的数量
	public int getCount()
	{
		return danjia.size();
	}
	//显示弹夹内子弹的列表
	public void display()
	{
		for(Ball a:danjia)
		{
//			System.out.println(a);
			a.print();
		}
	
	}

}
package eleven;

public class Test {
	public static void main(String[] args)
	{
		Gun li=new Gun();
		//开始装弹
		System.out.println("开始装弹");
		int index;
		for(index=1;index<=6;index++) 
		{
			Ball danjia=new Ball(index,"M54");
			try {
				li.load(danjia)
				;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
		}
		System.out.println("弹夹子弹序列");
		li.display();
		System.out.println("开始射击");
		while(true)
		{
			try {
				Ball danjia=li.shooting();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
		}
	}

}
刘兴梅

任务已更新

刘兴梅

任务已更新