Passenger
和TrainCoach
,并从TrainCoach
String[]
的对象
定义一个类Passenger
,其中包含字段名称(String
),年龄(int
),性别(char
:M / F),重量( int
)
定义一个包含TrainCoach
字段的班级Passenger[] passengers
。
定义类Train及其中的函数。班级火车有矢量教练。 给定Vector作为输入,创建对象Train,其中每个String []类似于上面作为TrainCoach输入的那个。
以下就是我所做的。但是我陷入了火车课。我没有得到如何将矢量对象传递给main方法。我试过以下:
乘客等级:
package Passenger;
public class Passenger {
String name;
int age;
char gender;
int weight;
public Passenger(){}
public Passenger(String data){
String[] s=data.split(":");
this.name=s[0];
this.age=Integer.parseInt(s[1]);
this.gender=s[2].charAt(0);
this.weight=Integer.parseInt(s[3]);
}
public Passenger[] makePassenger(String[] input){
Passenger[] passengers=new Passenger[input.length];
for(int i=0;i<input.length;i++){
passengers[i]=new Passenger(input[i]);
}
return passengers;
}
}
TrainCoach课程: 包裹乘客;
public class TrainCoach {
Passenger[] passengers;
static char gender;
public TrainCoach(){}
public TrainCoach(Passenger[] passengers){
this.passengers=passengers;
}
public TrainCoach(String[] data){
Passenger[] passengers=new Passenger[data.length];
for(int i=0;i<data.length;i++){
passengers[i]=new Passenger(data[i]);
}
this.passengers=passengers;
}
public static class PassengerTest{
public static void main(String[] args){
String[] str={"Amit Sharma:24:M:72","Rahul:12:M:55"};
Passenger pass=new Passenger();
Passenger[] passenger=pass.makePassenger(str);
TrainCoach traincoach=new TrainCoach(passenger);
int c=traincoach.numberOfPassengers();
int d=traincoach.numberOfChildren();
int b=traincoach.totalWeight();
int a=traincoach.numberOf(gender);
System.out.print(c+","+d+","+b+","+a);
}
}
public int numberOfPassengers(){
return this.passengers.length;
}
public int numberOfChildren(){
int count=0;
for(int i=0;i<passengers.length;i++){
if(passengers[i].age < 16){
count++;
}
}
return count;
}
public int totalWeight(){
int sum=0;
for(int i=0;i<passengers.length;i++){
sum+=passengers[i].weight;
}
return sum;
}
public int numberOf(char gender){
int count=0;
for(int i=0;i<passengers.length;i++){
if(passengers[i].gender=='M'){
count++;
}
else if(passengers[i].gender=='F'){
count++;
}
}
return count;
}
}
培训班:
package Passenger;
import java.util.Vector;
public class Train{
Vector<TrainCoach>coaches;
public Train(){}
public Train(Vector<String[]> data){
for(int i=0;i<data.size();i++){
coaches.addElement(new TrainCoach(data.elementAt(i)));
}
this.coaches=coaches;
}
public static class PassTrain{
public static void main(String[] s){
Passenger p=new Passenger();
Passenger[] passenger =p.makePassenger(s);
Vector<String[]> tc=new Vector<String[]>();
tc.addAll(tc);
Train t=new Train(tc);
int c=tc.numberOfPassengers();
System.out.print(c);
}
}
public int numberOfPassengers(){
int numOfPassengersInTrain = 0;
for(int i = 0; i < coaches.size(); i++){
numOfPassengersInTrain += this.coaches.elementAt(i).numberOfPassengers();
}
return(numOfPassengersInTrain);
}
}