0

Alright I know the title is really vague but I can't wrap my head around how to word my problem and therefore I can't google it; that's why I'm asking you guys

Basically I have a constructor that takes a file input and depending on the file name (in my example we're using file.txt or employees.txt) we do something to it. Now I have no idea if this is even a good idea or not or if there is another way to do multiple duplicate constructors. Here's my code so far and thanks for helping me out!:

public class CarDealershipSystem {

    public CarDealershipSystem(File file) {

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            ArrayList<Car> carObjectArray = new ArrayList<Car>();
            while((br.readLine()) != null) {

                if (file == cars.txt) {
                    String line = br.readLine();
                    String[] lineArray = line.split(",");

                    Car car = new Car();
                    car.setMake(lineArray[0]);
                    car.setModel(lineArray[1]);

                    carObjectArray.add(car);
                }
                else if (file == employees.txt) {
                    ;
                }
            }

        }catch(IOException e) {
            e.getLocalizedMessage();
            e.printStackTrace();
        }
    }
}  
Bashir
  • 2,057
  • 5
  • 19
  • 44
Vince
  • 109
  • 2
  • 9

1 Answers1

3

The simple answer is

if (file.getName().equals("cars.txt")) {
    ...
else if (file.getName().equals("employees.txt")) {
    ...
}

But there are some deeper problems here:

  1. It seems odd (wrong!) to have a single method or constructor that reads a file that can have two completely different formats ... and meanings.

  2. It seems odd (wrong!) that you can construct a car dealership with either only cars, or only employees. A car dealership needs to have both cars and employees

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Also, it seems odd to handle something like this based on the filename. IMHO: The caller should be free to give you any File he wants, as long as the content matches your expectations. The caller should be able to tell you what you should expect in that file – Felix May 04 '20 at 08:47
  • Thanks, this is for a school assignment and from his wording it sounded like he wanted us to use one constructor for both. I emailed him though so hopefully he clarifies. Thanks for your response! – Vince May 04 '20 at 09:01
  • *"... from his wording it sounded like he wanted us to use one constructor for both."* - So shouldn't the constructor have two `File` parameters?? – Stephen C May 04 '20 at 09:08
  • @StephenC that's possibly what he meant. I don't know why I didn't think of that haha thanks! – Vince May 04 '20 at 09:28