0

Hey i was wondering how can i create a table of objects in java using a text file I've created my table

Table tab[] = new Table[6]

and here's my text file :

id|des|pr

50 | Internet Fibre 50                          | 40.00

150| Internet Fibre 150                         | 50.00

500| Internet Fibre 500                         | 90.00

B  | Forfait Bien                               | 60.00

T  | Forfait Très Bien                          | 40.00

E  | Forfait Excellent                          | 30.00

I've created my table

Table tab[] = new Table[6]

I'd like to read each line (except the first line ) and make it an object (the type is Table) in the table above (tab) by sperating the "|" on each line so i'll have 6 objects in total each one will follow this constructor

Table newTable = new Table(id , des , pr); 

Thanx !

1 Answer 1

1

Try the below code:

Main.java

    Table[] tabs = new Table[6];
    BufferedReader bufferedReader = new BufferedReader(new FileReader("File location")); // add your file location here
    bufferedReader.readLine(); // ignoring the header line
    String row = bufferedReader.readLine();
    int count = 0;
    while (row != null) {
        String[] split = row.split("\\|");
        tabs[count]  = new Table(split[0].trim().replace("\\t", ""), split[1].trim().replace("\\t", ""), Double.parseDouble(split[2].trim().replace("\\t", "")));
        count++;
        row = bufferedReader.readLine();
    }

Table.java

public class Table {
    private String id;
    private String des;
    private double price;

    public Table(String id, String des, double price) {
        this.id = id;
        this.des = des;
        this.price = price;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Table{" +
                "id='" + id + '\'' +
                ", des='" + des + '\'' +
                ", price=" + price +
                '}';
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanx for ur answer ! but it didn't work for me i tried to catch the exceptions but still didn't work. Did u try it urself ?
Add the exception
i added it but still didn't work
I mean add the stack trace of the exception that you are getting.

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.