关于java面向对象问题
发布网友
发布时间:2023-10-28 20:03
我来回答
共2个回答
热心网友
时间:2024-01-09 02:07
说的并不是很清楚,你的说法给我感觉似乎是每个机房里只有一种机型,但是这在现实中并不一定,所以我想以我的想法给出我的程序。
Machine类
public class Machine {
private String name;
private double price;
Machine(String s , double p){
name = s;
price = p;
}
public String GetName(){
return name;
}
public double GetPrice(){
return price;
}
}
MachineRoom类
import java.util.*;
public class MachineRoom {
private int num;
private Map<String , Integer> m = new TreeMap<String , Integer>();//用来存储机房内所有机器的名字和数量
private List<Machine> l = new ArrayList<Machine>();//用来存储机房内所有机器的种类
private int flag = 0;
MachineRoom(int num , Machine... M){
this.num = num;
for(Machine mm : M){
m.put(mm.GetName(), 0);
l.add(mm);
}
}//构造函数,设置机房总的机器数量,和所有的机器种类
public Map<String , Integer> GetMachineRoomMap(){
return m;
}
public List<Machine> GetMachineRoomList(){
return l;
}
public void SetMachine(int number , Machine machine){
int value = m.get(machine.GetName());
m.put(machine.GetName(), number+value);
flag = flag + number;
}//设置每种机型的数量
public boolean ThatIsAll(){
return flag==num;
}//设置flag判断每种机型数量加起来是否和总数量相同
}
测试类
public class TestMachineRoom {
private double TotalPrice = 0;
public double GetAllPrice(MachineRoom M){
for(Machine machine : M.GetMachineRoomList()){
int typenum = M.GetMachineRoomMap().get(machine.GetName());
TotalPrice += typenum*machine.GetPrice();
}
return TotalPrice;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
TestMachineRoom test = new TestMachineRoom();
Machine M1 = new Machine("M1",15.00);
Machine M2 = new Machine("M2",16.00);
Machine M3 = new Machine("M3",17.00);
Machine M4 = new Machine("M4",18.00);//声明所有的机型
MachineRoom MR = new MachineRoom(56,M1,M2,M3,M4);//机房构造函数
MR.SetMachine(14, M1);
MR.SetMachine(14, M2);
MR.SetMachine(14, M3);
MR.SetMachine(14, M4);//设置各种机型的数量
if(MR.ThatIsAll()){//判断以上设置的机型总数量是否和构造函数中的总数量相同
System.out.println(test.GetAllPrice(MR));
}else{
System.out.println("机型总数量错误!");
}
}
}
热心网友
时间:2024-01-09 02:07
public class Machine{
private String name;
private int price;
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
public void setPrice(int p){
price = p;
}
public int getPrice(){
return price;
}
}
public class MachineRoom{
private int num;
private Machine machine;
public void setNum(int x){
num = x;
}
public int getNum(){
return num;
}
public void setMachine(Machine y){
machine = y;
}
public Machine getMachine(){
return machine;
}
}
public class Test{
public static void main(String[] args){
Machine m = new Machine();
m.setName("NO.1");
m.setPrice(4500);
MachineRoom mr = new MachineRoom();
mr.setNum(35);
mr.setMachine(m);
int AllPrice = Test.getAllPrice(mr);
System.out.println(AllPrice);
}
public static int getAllPrice(MachineRoom mr){
int price = (mr.getMachine().getPrice())*(mr.getNum());
return price;
}
}