简体   繁体   English

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

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

I have a car class and its constructor looks like this: 我有一个汽车类,它的构造函数如下所示:

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;
    }

The constructor is initialized in another class(main) when I press for create car from the menu. 当我从菜单按创建汽车时,构造函数在另一个类(主)中初始化。

The parameters of the constructor are all created/initiated by methods in the car class. 构造函数的参数全部由car类中的方法创建/启动。 The system should be the one giving the information like(the ID, position and time in). 该系统应该是提供诸如(ID,位置和时间)之类的信息的系统。

The problem is that the car object have not be initialized yet so I can't get the methods to work. 问题是汽车对象尚未初始化,因此我无法使用这些方法。

But I really need the cars object to contain its information(like car ID:CR1). 但是我确实需要汽车对象包含其信息(例如汽车ID:CR1)。

The information are all strings except for the time. 该信息是除时间以外的所有字符串。

How can I do that? 我怎样才能做到这一点?

PS: Im new to programming. PS:我是编程新手。 At first I was using static but it turns out static methods cause another bigger trouble with my code. 起初我使用的是静态方法,但事实证明静态方法会给我的代码带来更大的麻烦。

I posted something where there was my static methods and everyone told me to remove the statics. 我张贴了一些有我的静态方法的内容,每个人都告诉我要删除这些静态方法。

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);
    }
}

This is what is called when I want to create a new car. 当我要创建新车时,这就是所谓的。

I also put the whole car class in case you need it: 我还把整个汽车课都放在了您需要的地方:

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);
        }
    }

I attach you a code that can help you: 我附上了可以帮助您的代码:

first as all the parameters can be statics i move then to the constructor. 首先,因为所有参数都可以是静态变量,所以我将其移至构造函数。

second i move the static method "createCarsID();" 第二,我移动静态方法“ createCarsID();” to a static init block, in order to avoid unwanted calls. 到一个静态初始化块,以避免不必要的调用。

The example is fully functional. 该示例功能齐全。

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);
    }
}

Finally in order to call this function: 最后为了调用这个函数:

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.

相关问题 从另一个类调用非静态方法 - Call non static methods from another class 从另一个类调用非静态void - Call a non static void from another class 如何从另一个类调用非静态抽象方法 - How to call a non static abstract method from another class 如何从Android中的另一个类调用非静态变量? - How to call a non static variable from another class in Android? 构造函数中的一类静态方法 - Constructor in a class of static methods 我们能否将 Arraylist 从 class 调用到另一个 class,并且可以被“另一个”class 中的所有方法使用? 无 static - Java - Can we call a Arraylist from a class to another class, and can be used by all methods in the 'another' class? No static - Java 如何在非静态方法中从另一个类调用非静态方法? (java) - How do I call a non-static method from another class in a non-static method? (java) 调用另一个类的非静态方法 - Call non-static method of another class 使用所有非静态方法但没有非静态字段的类是否有意义? (或所有静态字段和方法以及构造函数) - Is there a point to having a class with all non-static methods but no non-static fields? (or all static fields and methods along with a constructor) 从外部类非静态构造函数访问内部类的静态方法 - Accessing static methods of inner class from an outer class nonstatic constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM