描述
【描述】
(1)聲明并實作一個名為Vehicle的類,表示汽車。Vehicle類包括:
int類型的私有資料域passengers,表示載客數量。
int類型的私有資料域fuelcap,表示油箱容量(機關:加侖)。
int類型的私有資料域mpg,表示油耗均值(每加侖燃油可以跑多少英裡,miles per gallon)。
有參構造方法,将載客數量、油箱容量、油耗均值設定為給定的參數。
通路器方法getPassengers、getFuelCap、getMPG,分别用于通路載客數量、油箱容量、油耗均值。
更改器方法setPassengers、setFuelCap、setMPG,分别用于更改載客數量、油箱容量、油耗均值。
成員方法range,顯示汽車行駛的英裡數。
成員方法fuelneeded,根據汽車要行駛的英裡數,傳回所需汽油的加侖數。
(2)卡車是汽車的一種,卡車的一個重要屬性就是它的運載能力。從Vehicle類派生出Truck類,表示卡車。Truck類新增int類型的私有資料域cargocap(機關:磅)以及有參構造方法,将載客數量、油箱容量、油耗均值、運載能力設定為給定的參數;通路器/更改器方法getCargo和setCargo。
Vehicle類的定義應該這樣開始:
class Vehicle {
也就是說,Vehicle類的class前面不要有public。
Truck類的定義應該這樣開始:
class Truck extends Vehicle {
也就是說,Truck類的class前面不要有public。
【輸入】
第一行輸入載客數量、油箱容量、油耗均值、運載能力。
第二行輸入汽車要行駛的英裡數。
【輸出】
見【輸出示例】
【輸入示例】
2 200 7 44000
252
【輸出示例】
Truck can carry 44000 pounds.
To go 252 miles truck needs 36.0 gallons of fuel.
import java.util.Scanner;
class Vehicle {
private int passengers;
private int fuelcap;
private int mpg;
public Vehicle(int a,int b,int c)
{
passengers=a;
fuelcap=b;
mpg=c;
}
public int getFuelcap() {
return fuelcap;
}
public int getMpg() {
return mpg;
}
public int getPassengers() {
return passengers;
}
public void setFuelcap(int fuelcap) {
this.fuelcap = fuelcap;
}
public void setMpg(int mpg) {
this.mpg = mpg;
}
public void setPassengers(int passengers) {
this.passengers = passengers;
}
public void range()
{
System.out.println(mpg*fuelcap);
}
public double fuelneeded(int dis)
{
return dis*1.0/(mpg*1.0);
}
}
class Truck extends Vehicle {
private int cargocap;
public Truck(int a,int b,int c,int d)
{
super(a,b,c);
cargocap=d;
}
public int getCargocap() {
return cargocap;
}
public void setCargocap(int cargocap) {
this.cargocap = cargocap;
}
}
public class test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int d= sc.nextInt();
int e= sc.nextInt();
//sc.close();
Truck aa=new Truck(a,b,c,d);
System.out.printf("Truck can carry %d pounds.\n",d);
System.out.printf("To go %d miles truck needs %.1f gallons of fuel.\n",e,aa.fuelneeded(e)*1.0);
}
}