I am trying to read a file which contains a product description, productCode and a productPrice. I have it so that it will set the variables of Product with each new line until it equals null:
public class ReadFile {
static ArrayList<Product> products = new ArrayList<Product>();
public static void main(String[] args){
String line;
try {
BufferedReader bufferedReader = new BufferedReader (new FileReader("C:/Users/Tom/Desktop/data.txt"));
while ((line = bufferedReader.readLine()) != null){
Product product = new Product();
product.setDescription(bufferedReader.readLine());
product.setProductCode(bufferedReader.readLine());
product.setUnitPrice(Integer.parseInt(bufferedReader.readLine()));
System.out.println(product);
products.add(product);
}
bufferedReader.close();
}
catch(IOException e){
System.out.println("File not found.");
}}
However I get a error when It comes to getting the next product in the file (Pear):
Exception in thread "main" java.lang.NumberFormatException: For input string: "Pear"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at controller.ReadFile.main(ReadFile.java:24)
This is how the file is set out:
Apple /r 01 /r 99 /r Pear /r 02 /r 88
Note: /r Used to represent new line in file.
Where am I going wrong so that it will create a new Product, set the information and repeats until the line equals null?
You're reading twice for the Product type. Just use the value of line
variable to set the Product Description.
while ((line = bufferedReader.readLine()) != null){
// line has already stored information about the Product type.
Product product = new Product();
product.setDescription(line); // set value using line variable
// product.setDescription(bufferedReader.readLine()); // error
product.setProductCode(bufferedReader.readLine());
product.setUnitPrice(Integer.parseInt(bufferedReader.readLine()));
System.out.println(product);
products.add(product);
}