繁体   English   中英

从构造函数中的另一个类调用非静态方法

[英]Call non static methods from another class in constructor

我有一个汽车类,它的构造函数如下所示:

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

当我从菜单按创建汽车时,构造函数在另一个类(主)中初始化。

构造函数的参数全部由car类中的方法创建/启动。 该系统应该是提供诸如(ID,位置和时间)之类的信息的系统。

问题是汽车对象尚未初始化,因此我无法使用这些方法。

但是我确实需要汽车对象包含其信息(例如汽车ID:CR1)。

该信息是除时间以外的所有字符串。

我怎样才能做到这一点?

PS:我是编程新手。 起初我使用的是静态方法,但事实证明静态方法会给我的代码带来更大的麻烦。

我张贴了一些有我的静态方法的内容,每个人都告诉我要删除这些静态方法。

public void addCar() {

    Cars car1 = new Cars(car1.getID(), car1.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
    myGarage.add(car1);
    if(!(car1.getAssignedTo()).equals(null)){
        car1.getAssignedTo().setAssign(car1);
        car1.getAssignedTo().setAvailable(false);
    }
}

当我要创建新车时,这就是所谓的。

我还把整个汽车课都放在了您需要的地方:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import javax.swing.text.Position;

public class Cars {

    private String carID;
    private String plateNum;
    private String position;
    private 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;
        this.position = position;
        this.assignedTo = assignedTo;
        this.currTime = currTime;
    }

    public void createCarsID() {

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

    public 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 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) {
        int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
        int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
        int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
        return String.format("%02d:%02d:%02d", hrs, min, sec);
    }

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

我附上了可以帮助您的代码:

首先,因为所有参数都可以是静态变量,所以我将其移至构造函数。

第二,我移动静态方法“ createCarsID();” 到一个静态初始化块,以避免不必要的调用。

该示例功能齐全。

package test;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import javax.swing.text.Position;

public class Cars {

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

static{
    createCarsID();
}

public Cars() {
    this.carID = Cars.getID();
    this.plateNum = Cars.askCarID();
    this.position = Cars.generatePosition();
    this.assignedTo = Attendant.askForAtt();
    this.currTime = System.currentTimeMillis();
}

public static void createCarsID() {

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

public static String getID() {


    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 String generatePosition() {


    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));
            return getPos(tempPos);
            //tempArray2.get(x) = null;

        }
    }
    return null;
}

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

}

public String getPlateNum() {
    return plateNum;
}


public String getCarID() {
    return carID;
}

public String getPosition() {
    return position;
}

public long getCurrTime() {
    return currTime;
}

public 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) {
    int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
    int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
    int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
    return String.format("%02d:%02d:%02d", hrs, min, sec);
}

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

最后为了调用这个函数:

package test;
public class main {
public static void main(String [] args){
    main test = new main();
    test.addCar();

}
public void addCar() {

    Cars car1 = new Cars();
    Garage myGarage = new Garage();
    myGarage.add(car1);
    if(!(car1.getAssignedTo()).equals(null)){
        car1.getAssignedTo().setAssign(car1);
        car1.getAssignedTo().setAvailable(false);
    }
}   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM