定義具有的字段名稱(字符串),年齡(INT),性別類乘客(CHAR:M/F),重量(INT)如何從主類調用一個類?
定義具有字段乘客一類TrainCoach []乘客
定義類列車和它的功能。班級培訓有Vector教練。 給定的矢量作爲輸入,創建對象列車其中每個String []類似於給予作爲輸入上面TrainCoach之一。
我在調用主類的Train類的函數時遇到了麻煩,我該如何調用這些方法?
客車類:
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類:
package Passenger;
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 int numberOfPassengers(){
int numOfPassengersInTrain = 0;
for(int i = 0; i < coaches.size(); i++){
numOfPassengersInTrain += this.coaches.elementAt(i).numberOfPassengers();
}
return(numOfPassengersInTrain);
}
}
可你寫的錯誤味精?! – Scorpion
請確切指出哪條線路發生故障併發生什麼錯誤? – merlin2011
錯誤 - *無法找到或加載主要班級乘客* ...我無法將其與主班級鏈接。 –