简体   繁体   中英

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. The system should be the one giving the information like(the ID, position and time in).

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).

The information are all strings except for the time.

How can I do that?

PS: Im new to programming. 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();" 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);
    }
}   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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