实验内容
火车要装载一批货物和乘客,货物由3种商品:电视、计算机和洗衣机组成。火车需要计算出所装载的货物和乘客的总重量。
要求:有一个SetAndGetWeight接口,该接口中有2个方法:
public double getWeight();
public void setWeight(double weight);
有四个实现该接口的类:Television、Computer、WashMachine、People类。这四个类通过实现接口设置各对象的自重和获取对象的自重。
有一个Train类,该类用SetAndGetWeight接口类型的数组作为成员,那么该数组的单元就可以存放Television、Computer、WashMachine、People对象的引用。程序能输出Train对象所装载的货物和乘客的总重量。
程序的效果图如下:
答案代码
package com.dreamchaser.work7;
import java.util.Scanner;
class Television implements SetAndGetWeight {
double weight;
public void setWeight(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
class Computer implements SetAndGetWeight{
double weight;
public void setWeight(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
class WashMachine implements SetAndGetWeight{
double weight;
public void setWeight(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
class People implements SetAndGetWeight{
double weight;
public void setWeight(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
class Train {
SetAndGetWeight[] things;
double totalWeight=0;
Train(SetAndGetWeight[] things) {
this.things=things;
}
public double getTotalWeight() {
totalWeight=0;
for(int i=0;i<things.length;i++)
{
totalWeight+=things[i].getWeight();
}
return totalWeight;
}
}
class TrainComputerWeight{
public static void main(String args[]) {
int peoplenum = 0, tvnum = 0, computernum = 0, washnum = 0, totalnum = 0;
Scanner reader = new Scanner(System.in);
System.out.println("请输入乘客的人数:");
peoplenum = reader.nextInt();
System.out.println("请输入电视机的数量:");
tvnum = reader.nextInt();
System.out.println("请输入电脑的数量:");
computernum = reader.nextInt();
System.out.println("请输入洗衣机的数量:");
washnum = reader.nextInt();
totalnum = peoplenum + tvnum + computernum + washnum;
SetAndGetWeight[] things = new SetAndGetWeight[totalnum];
Train train = new Train(things);
System.out.println("请输入乘客的体重:");
for (int i = 0, k = 1; i < peoplenum; i++, k++) {
things[i] = new People();
System.out.println("请输入第" + k + "个乘客的体重:");
things[i].setWeight(reader.nextDouble());
}
System.out.println("请输入电视机的重量:");
for (int i = peoplenum, k = 1; i < peoplenum + tvnum; i++, k++) {
things[i] = new Television();
System.out.println("请输入第" + k + "个电视机的重量:");
things[i].setWeight(reader.nextDouble());
}
System.out.println("请输入电脑的重量:");
for (int i = peoplenum + tvnum, k = 1; i < peoplenum + tvnum + computernum; i++, k++) {
things[i] = new Computer();
System.out.println("请输入第" + k + "个电脑的重量:");
things[i].setWeight(reader.nextDouble());
}
System.out.println("请输入洗衣机的重量:");{
for (int i = peoplenum + tvnum + computernum, k = 1; i < peoplenum + tvnum + computernum + washnum; i++, k++) {
things[i] = new WashMachine();
System.out.println("请输入第" + k + "个洗衣机的重量:");
things[i].setWeight(reader.nextDouble());
}
}
System.out.println("火车装在的总重量::" + train.getTotalWeight());
}
}