从另一个类调用非静态方法

时间:2016-09-22 20:48:18

标签: java static

我有两节课。 CarAttendant

public Attendant(int staffNum, String id, boolean available, attNm name, Cars assign) {
    this.staffNum = staffNum;
    this.id = id;
    this.available = available;
    this.name = name;
    this.assign = assign;
}

public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
    this.carID = carID;
    this.plateNum = plateNum;
    Cars.position = position;
    Cars.assignedTo = assignedTo;
    this.currTime = currTime;
}

我的获奖者是用for循环创建的:

createIDList();
int staffAmount = getStaffAmount();

for (int x = 0; x < staffAmount; x++) {
    Attendant att = new Attendant(x + 1, Attendant.tempArray[x], true, attNm.getNm(), null);
    myAtt.add(att);
}
for (int x = 0; x < myAtt.size(); x++) {
    System.out.println(myAtt.get(x));
}

所有参数都来自一个从ArrayList获取它们的函数。所有服务员都有相同的名字。

汽车也一样。 每次我创造一辆汽车,它都来自一个功能,汽车将有他们的名字:汽车

当他们被创建时,我的服务员和我的车被加入他们的ArrayList(ArraylistCar和arraylistAtt)

但是当我创造新车时,所有车辆都输出相同的ID,并且错误地输出了服务员的详细信息。

有人告诉我静态方法和变量是这个问题的原因。所以我试图删除一些静态但我得到错误。 如果我使用getID方法删除静态,我无法在话务员类中调用它。 当我使用方法作为参数创建一个新类时,这些情况也会发生(方法不再是静态的,所以我不能从另一个类中调用它们。)

请帮助我,我被困住了。我知道很久我尝试了不同的方法,但没有任何效果。 我也提出了toString()方法,以防它们出现问题。 有些人告诉我也要把我的整个代码和输出,所以如果你需要的话,它完全在下面。

车:

@Override
public String toString() {
    return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId() 
    + "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}

Attandant:

@Override
public String toString() {
    return "Attendant [staffNum=" + staffNum + ", id=" + id + ", available=" + available + ", name=" + name
            + ", Car=" + assign + "]";
}

PS:英语不是我的母语。

我的整个代码在这里:

public class Cars {

    private static String carID;
    private String plateNum;
    private static String position;
    private static Attendant assignedTo;
    private long currTime;
    static ArrayList<String> tempArray2 = new ArrayList<String>();

    public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
        this.carID = carID;
        this.plateNum = plateNum;
        Cars.position = position;
        Cars.assignedTo = assignedTo;
        this.currTime = currTime;
    }

    private static void createCarsID() {
        for (int x = 0; x < Garage.getCarsCapacity(); x++) {
            String tempCarID = ("CR" + (x + 1));
            tempArray2.add(tempCarID);
        }
    }

    public static String getID() {
        createCarsID();
        String tempID = null;
        String tempPos = null;
        for (int x = 0; x < Garage.getCarsCapacity(); x++) {
            if (tempArray2.get(x) != null) {
                tempID = tempArray2.get(x);
                tempPos = tempArray2.get(x);
                tempArray2.remove(tempArray2.get(x));
                getPos(tempPos);
                //tempArray2.get(x) = null;
                break;
            }
        }
        return tempID;
    }

    public static void getPos(String IdToPos) {
        String strPos = IdToPos.substring(2);
        int pos = Integer.parseInt(strPos);
        position = "GR" + pos;
    }

    public String getPlateNum() {
        return plateNum;
    }

    public static String getCarID() {
        return carID;
    }

    public static String getPosition() {
        return position;
    }

    public long getCurrTime() {
        return currTime;
    }
    public static Attendant getAssignedTo() {
        return assignedTo;
    }

    public static String askCarID() {
        boolean valid = false;
        System.out.println("Please enter your car's plate number.");
        Scanner scanCarID = new Scanner(System.in);
        String scannedCarID = scanCarID.nextLine();
        while (!valid) {
            if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
                valid = true;
                System.out.println(scannedCarID);
            } else {
                System.out.println("Please enter a valid plate number. Ex: AF 378");
                askCarID();
            }
        }
        return scannedCarID.toUpperCase();
    }

    public String convert(long miliSeconds) {
        ...
    }

    @Override
    public String toString() {
        return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId() 
        + "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
    }
}

public class Attendant {

    private static int staffAmount = 10;

    public int staffNum;
    private String id;
    private boolean available;
    private attNm name;
    private Cars assign;

    private String user;
    static String[] tempArray = new String[staffAmount];
    static ArrayList<Attendant> myAtt = new ArrayList<Attendant>();

    public Attendant(int staffNum, String id, boolean available, attNm name, Cars assign) {
        this.staffNum = staffNum;
        this.id = id;
        this.available = available;
        this.name = name;
        this.assign = assign;
    }

    public Attendant(String user) {
        this.user = user;
    }

    public static void createAtt() {
        createIDList();
        int staffAmount = getStaffAmount();

        Attendant att = null;
        for (int x = 0; x < staffAmount; x++) {
            att = new Attendant(x + 1, Attendant.tempArray[x], true, attNm.getNm(), null);
            myAtt.add(att);
        }

        for (int x = 0; x < myAtt.size(); x++) {
            System.out.println(myAtt.get(x));
        }
    }

    public static void startWork() {
        createAtt();
    }

    public static Attendant askForAtt() {
        Scanner scanAtt = new Scanner(System.in);
        Random randAtt = new Random();
        //Attendant  asnAtt = null;
        System.out.println("Do you require an Attendant ? Y or N");
        String response = scanAtt.next();
        if ((response.equals("y")) || (response.equals("yes")) || (response.equals("Yes")) || (response.equals("Y"))) {
            // Cars.setAssignedTo(myAtt.get(randAtt.nextInt(myAtt.size())));
            Attendant attendant = myAtt.get(randAtt.nextInt(myAtt.size()));
            while(!attendant.isAvailable()){
                attendant = myAtt.get(randAtt.nextInt(myAtt.size()));
            }
            return attendant;

        } else if ((response.equals("n")) || (response.equals("no")) || (response.equals("No")) || (response.equals("N"))) {
            return new Attendant ("User");
        }
        return new Attendant ("User");    //If input is neither Yes nor No then return new Attendant    
    }

    public static void assignCarAtt(){

    }

    public int getStaffNum() {
        return staffNum;
    }

    public static int getStaffAmount() {
        return staffAmount;
    }

    public void setStaffNum(int staffNum) {
        this.staffNum = staffNum;
    }

    public void setAvailable(boolean available) {
        this.available = available;
    }

    public boolean getAvailable(){
        return available;
    }

    public void setAssign(Cars assign) {
        this.assign = assign;
    }

    public String getId() {
        return id;
    }

    public boolean isAvailable() {
        return available;
    }

    public attNm getName() {
        return name;
    }

    public static void createIDList() {
        for (int x = 0; x < staffAmount; x++) {
            tempArray[x] = ("Att" + (x + 1));
        }
    }

    public String strAssignAttCar(Cars assign){
        String result = null;
        if(assign!=null){
            result = Cars.getCarID();
        }
        return result;
    }

    @Override
    public String toString() {
        return "Attendant [staffNum=" + staffNum + ", id=" + id + ", available=" + available + ", name=" + name
                + ", Car=" + assign + "]";
    }

}

车库类打印;

  Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att10(Ava) Parked at:18:32:08, Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]
   // Should have been like that:
    Car:HU 457 ID:CR1 Position:GR1 Assigned to:Att10(Ava) Parked at:18:32:08, Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]

服务员班级打印;

    Attendant [staffNum=9, id=Att9, available=false, name=Elizabeth, Car=Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]
    Attendant [staffNum=10, id=Att10, available=false, name=Ava, Car=Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att10(Ava) Parked at:18:32:08]
   // Should have been like that:
    Attendant [staffNum=9, id=Att9, available=false, name=Elizabeth, Car=Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]
    Attendant [staffNum=10, id=Att10, available=false, name=Ava, Car=Car:HU 457 ID:CR1 Position:GR1 Assigned to:Att10(Ava) Parked at:18:32:08]

1 个答案:

答案 0 :(得分:2)

首先,让Cars类单数化,即Car更有意义。

背景信息:在语句Cars car1 = new Cars()中,Cars是类,car1Cars类的实例。这个问题是由混淆两个引起的。

静态变量/方法与类的任何特定实例无关;它只与班级相关联。因此,当您将carID声明为static时,您说只有一个全局Cars.carID,而不是许多car1.carIDcar2.carID等。确保实例变量/方法不是静态的。

删除static关键字时遇到的问题是因为您拨打的是Cars.getCarID()而不是car1.getCarID()。您需要将类上的所有方法调用更改为类的实例上的方法调用。

tl; dr:要解决此问题,请删除所有static个关键字,并将对Cars.getCarID()等方法的所有静态引用更改为car1.getCarID()

面向对象编程的示例(注意除了main方法之外没有静态方法或变量):

Car.java:

class Car {
    int id;
    int speed;

    Car(int id, int speed) {
        this.id = id;
        this.speed = speed;
    }

    int getSpeed() {
        return speed;
    }

    void setSpeed(int newSpeed) {
        speed = newSpeed;
    }

    int getId() {
        return id;
    }

    void goFast() {
        System.out.println("VROOM! This car is going so fast: " + speed);
    }
}

Person.java:

class Person {
    Car myCar;
    int id;

    Person(int id, Car car) {
        this.id = id;
        this.myCar = car;
    }

    int getCar() {
        return myCar;
    }

    int getId() {
        return id;
    }

    void floorIt() {
        myCar.setSpeed(myCar.getSpeed() + 10);

    void drive() {
        myCar.goFast();
    }
}

Main.java:

class Main {
    public static void main(String[] args) {
        Car ferrari = new Car(1, 1000);
        Car bmw = new Car(2, 500);

        Person alice = new Person(1, ferrari);
        Person bobby = new Person(2, bmw);

        alice.drive();
        bobby.drive();

        bobby.floorIt();
        bobby.drive();

    }
}