Reputation: 1
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 !
Upvotes: 0
Views: 287
Reputation: 1615
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 +
'}';
}
}
Upvotes: 1