刚刚学会封装盒子
对于汽车信息 在主视图展示选择按钮 在新增视图新增汽车信息 在查看视图显示汽车信息
将汽车信息存储在封装的盒子中 并进行拿出显示
封装的盒子代码如下:
package com.util;
import com.Box;
import com.Manager;
public class ArrayBox implements Box {
private Object[] elements;
private int index = 0;
public ArrayBox() {
elements = new Object[10];
}
public ArrayBox(int length) {
elements = new Object[length];
}
@Override
public boolean add(Object o) {
checkCapacity(1);
elements[index] = o;
index++;
return true;
}
@Override
public boolean add(Object[] objects) {
checkCapacity(objects.length);
for (int i = 0; i <objects.length ; i++) {
elements[index] = objects[i];
index++;
}
return true;
}
public void checkCapacity(int needCount) {
if (index + needCount > elements.length) {
//数组容量不足,需要扩容
//1创建一个更大的数组
//2将原数组中的元素,依次移动到新数组中
//3更新数组地址
int newLength = elements.length * 2;
if (newLength < index + needCount) {
newLength = index + needCount;
}
Object[] newArray = new Object[newLength];
for (int i = 0; i <index ; i++) {
newArray[i]=elements[i];
}
elements = newArray;
}
}
@Override
public Manager getManager() {
return null;
}
@Override
public int size() {
return index;
}
@Override
public void show() {
for (int i = 0; i <index ; i++) {
Object obj=elements[i];
System.out.println(obj.toString());
}
}
}
主视图代码
package com.view;
import java.util.Scanner;
public class MainView {
public void show(){
Scanner input= new Scanner(System.in);
System.out.println("----主页面----");
System.out.println("1.新建汽车信息");
System.out.println("2.显示汽车信息");
System.out.println("选择操作: ");
a:while (true){
int no=input.nextInt();
switch (no){
case 1:
AddView view=new AddView();
view.show();
break a;
case 2:
CkView view1=new CkView();
view1.show();
break a;
default:
System.out.println("无效操作 重新输入:");
break;
}
}
}
}
新增视图代码:
package com.view;
import com.Box;
import com.domain.Car;
import com.service.CarService;
import com.util.ArrayBox;
import java.util.Scanner;
public class AddView {
public void show(){
Scanner sc =new Scanner(System.in);
System.out.println("----新建汽车信息----");
System.out.println("汽车编号:");
int cno=sc.nextInt();
System.out.println("汽车名称:");
String cname=sc.next();
System.out.println("汽车颜色:");
String color=sc.next();
System.out.println("汽车价格:");
int price=sc.nextInt();
CarService c1=new CarService();
c1.add(cno,cname,color,price);
System.out.println("保存成功,按任意键继续.....");
sc.next();
MainView mainView=new MainView();
mainView.show();
}
}
查看视图代码:
package com.view;
import com.Box;
import com.domain.Car;
import com.service.CarService;
import java.util.Scanner;
public class CkView {
public void show() {
Scanner sc =new Scanner(System.in);
System.out.println("----汽车信息列表----");
CarService carService = new CarService();
Box c1 = carService.show();
c1.show();
System.out.println("查看成功:按任意键继续.....");
sc.next();
MainView mainView=new MainView();
mainView.show();
}
}
运行结果: