0

I have a class "car", having five parametres of car (str brand, str model, str colour, int power, int tank), and I have a .txt with five cars, written like that:

Toyota Supra Black 280 80
Ferrari F430 Red 510 95
Nissan GT-R White 600 71
Koenigsegg Agera White 940 80
Mazda RX-8 Red 231 62

I have to read this list from file and make an array of lines array (cars), while each car array is an array of 5 parametres, like: Cars[car][parametres], and push it into a object of a class (should be a peace of cake, and i think i can handle this)

But i have no clue how to deal with array. Only thing i have now is reading from file:

void 123() {
    String[] ImpData = null;
    try {
        String str;
        BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
        br.close();
    } catch (IOException exc) {
        System.out.println("IO error!" + exc);
    }
}

Any suggestions?

6
  • Hint: try to split line on space. Commented Sep 24, 2015 at 20:42
  • First, I'm assuming 123 is just for this posting because that's not a valid method name. Second, if you don't know the number of cars in the file (which I'd assume is the case), it will be easier to accumulate things using some sort of List, I'd choose an ArrayList. Check the javadocs for those to see how to add elements to them and to convert them to real arrays. To get the inner arrays, look at String.split, although you might have to worry about names with spaces in them (Alfa Romeos for example). Commented Sep 24, 2015 at 20:43
  • @genesi5 Is using array a strict requirement? Because it actually doesn't make sense to use 2D array to store data like this. Commented Sep 24, 2015 at 20:49
  • @genesi5 I have updated my solution with using array. You can take a look at it. Leave a comment if you have further questions. Commented Sep 24, 2015 at 21:05
  • @bim ok, in order. 1) about 123 - yes, just a random for the post. 2) as i wrote in topic, i have to make a strict (n=5) array of objects of CAR class with 5 parametres, but before i'll be able to push the data into class object, i need to read and store it corectly. I tried list<string>, but then i wasn't able to dig the array an parametres properly because of type incompatibility, so that has screwed up. Split is also didn't worked well, so i consider 2D string array as the most suitable solution. But i can be wrong. Commented Sep 24, 2015 at 23:17

4 Answers 4

1

Create a list of Car object and adding each line into the list as 1 Car object each.

ArrayList<Car> list = new ArrayList<Car>();

while ((str = br.readLine()) != null) { //Not checking your loop 

    String[] tok = str.split(" ");  //str holds all car information
    list.add(new Car(tok[0], tok[1], tok[2], tok[3], tok[4]));
}

Assuming your Car class has a constructor which accepts the 5 arguments.


Edit: (To fit requirement of using Array)

When you use array, you have to pre-allocate a fixed array length first. Using array is not suitable for storing data from files because there can exist any number of lines of data. Anyway, to answer your question on using array:

String[][] data = new String[numRecords][5];  //numRecords equals total car objects
int x=0;    

while ((str = br.readLine()) != null) { //Not checking your loop 

    String[] tok = str.split(" ");  //str holds all car information
    data[x] = tok;   //Assign entire row of tok into data
    x++;
}

Once again, I seriously do not recommend reading data file into an array. If you really have to do so, you can pre-determine number of records in the text file first, then set the array size accordingly.

Side note: 2D arrays are also not a suitable data structure for storing data such as a car object with its own attributes.

Sign up to request clarification or add additional context in comments.

Comments

0

You want a two dimensional array. However, note that the array size must be known in advance and you don't know how many lines are in the file. So, first read everything into a secondary linked list data structure (you could also read the file twice, this is not efficient). Now you have all the strings, make a two dimensional array and then split each string into an array of tokens, using the " " delimiter. If you want to treat the tokens as integers and strings, you can use an array of Object instead and store Integer, String, etc. Off the top of my head, something like this follows - also note in your post, you can't start a method with numbers :)

String[] ImpData = null;
try {
    String str;
    List<String> allStrings = new LinkedList<String>();
    BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
    while ((str = br.readLine()) != null) {
        allStrings.add(str);
    }
    br.close();
    String[][] ImpData = new String[allStrings.size()][];
    for(int i=0; i<allStrings.size();i++){
        ImpData[i] = allStrings.get(i).split(" ");
    }

} catch (IOException exc) {
    System.out.println("IO error!" + exc);
}

2 Comments

System.out.printf("%s %s, %s", ImpData[3][0], ImpData[0][1], ImpData[3][2]);, printed out "Koenigsegg Supra, White". Look like it works. Thank you very much fo help =)
no problem - keep in mind, this style can lead to a ragged multidimensional array, which can sometimes be surprising
0

I think what you are looking for is a 2-dimensional array. The first dimension is the index for the car, the second are the 5 pieces that make it up. It looks like this: (not actual language, just a guide to build it.)

array is car[int][string, string, string, int, int]
car[0][Toyota,Supra,Black,280,80]
car[1][Ferrari,F430,Red,510,95]

So, referencing car[1] will tell you all about that car.

That's one idea, anyway...

1 Comment

Yes, exactly like that
0

for Car

class Car {
 public String brand, model, colour;
 int power, int tank;
}

structure

List<Car> cars = new ArrayLis<Car>()'

the most important part is safe analize line and fill part of data. The simplest (but not the best) is:

In out loop when You have line str line by line, set analyse:

String arg[] = str.split(" ");
Car c = new Car();
c.brand = arg[0];
c,model = arg[1];
c.color = arg[2];
c.power = Integer.parseInt(arg[3],0);
c.tank = Integer.parseInt(arg[4],0);

and then

cars.Add(c);

1 Comment

Seems to be useful, thaks =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.