Load .dat file and read

6.7k views Asked by At

I have text .dat file and I load this file from my main class and read in my DataReader class. but I get errors that i have to change my modifier to static. I can't do that because it is required to be non-static.

I am stuck here and not sue if my problem is here or somewhere else. will you check my codes and let me know if it is okay or not? next line also does not store in vehicle and shows null!!

this code gets the error:

if(DataReader.loadData(args[0])) {   // i get errors here

and ask me to change this to: public static boolean loadData(String VehicleData) { /// but this code has to be non-static... ( required by my professor)

Main class:

public class Project3 {

private static Vehicle[] vehicles;
static int x;

public static void main(String[] args) {
    // Display program information


    DataReader reader = new DataReader(); // The reader is used to read data from a file


    // Load data from the file
    **if(DataReader.loadData(args[0]))** {   // i get errors here

        vehicles= reader.getVehicleData(); // this line also shows null

        // Display how many shapes were read from the file
        System.out.println("Successfully loaded " + vehicles[0].getCount() + 
                           " vehicles from the selected data file!");
        displayMenu();
    }
}

DataReader Class:

ublic boolean loadData(String VehicleData) {
    boolean validData = false;
    String line;

try{
// Open the file
    BufferedReader reader = new BufferedReader(new FileReader("VehicleData.dat"));
//Read File Line by line


        while((line=reader.readLine()) !=null) {
            addVehicle(line.split(","));
        }
        reader.close();
        vehicles = Array.resizeArray(vehicles, vehicleCount);
        validData = true;
    }   
4

There are 4 answers

1
MadProgrammer On BEST ANSWER

You've create an instance of the reader but then chosen not to use it...

DataReader reader = new DataReader(); // The reader is used to read data from a file
if(DataReader.loadData(args[0]))

You should just use the instance you have available

DataReader reader = new DataReader(); // The reader is used to read data from a file
if(reader.loadData(args[0]))
0
ShyJ On

You should probably use the DataReader instance (reader) you create the line before:

    DataReader reader = new DataReader(); // The reader is used to read data from a file


    // Load data from the file
    if(reader.loadData(args[0])) {
0
Reimeus On

As loadData is an instance method you should use:

if (reader.loadData(args[0])) {
0
shaunw On

Yes, change DataReader to reader. You have created the DataReader object named reader but you are calling loadData() method on the class DataReader and not on the object reader. If you don't have an instance of the object and are calling the method it will have to be a static method. You can call static methods whenever you want, they do not have to be on a specific object.