i want to copy specific value from text file to Arraylist in Java Application. This is my text file( which is stored in my desktop as test.text)
String name = carrot;
double unit_price = 200;
int unit = 10;
This value i want to store in Arraylist, which is present in my main application as follow:
package com.main;
import com.collection.Ingridient;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
FileReader fin = new FileReader("/home/yati/Desktop/test");
Scanner src = new Scanner(fin);
// Read the ingridient from text file.
while (src.hasNext()) {
if (src.hasNext()) {
i_one.setName(src.next());
System.out.println("Name: " +src.next());
} else
if(src.hasNextDouble()) {
i_one.setUnit_price(src.nextDouble());
System.out.println("Unit Price: " +src.nextDouble());
}
else if (src.hasNextInt()) {
i_one.setUnit(src.nextInt());
System.out.println("Unit: " +src.nextInt());
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
fin.close();
}
}
Her, Ingridient class has following code:
package com.collection;
public class Ingridient {
String name;
Double unit_price;
int unit;
public Ingridient() {
name = null;
unit_price = null;
unit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setUnit_price(Double unit_price) {
this.unit_price = unit_price;
}
public void setUnit(int unit) {
this.unit = unit;
}
}
My problem is that my application can store only name in Ingridient object and it cannot store any value in unit and unit_price. Obtained output is:
I know i am mistaking somewhere but i cannot solve this issue. Any Suggestion?