I'm reading data from an external file with the CSV format. But this data is coming in String
format. There is a price field that I need to convert to double
for manipulation purposes.
Class Catalogs
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Catalog {
private ArrayList<Product> products = new ArrayList<Product>();
public ArrayList<Product> getProducts() {
return products;
}
public void setProducts(Product p) {
products.add(p);
}
public ArrayList<Product> showProducts(){
for(Product prod : products){
System.out.println("id:"+ prod.getId());
System.out.println("Price:"+ prod.getPrice());
}
return getProducts();
}
public static void main(String[] args){
File file = new File("C:\Users\casa\Desktop\catalog.csv");
String line = new String();
Product p = new Product();
Catalog c = new Catalog();
try {
Scanner reader = new Scanner(file);
while(reader.hasNext()){
line = reader.nextLine();
String[] value = line.split(",");
p.setId(value[0]);
p.setPrice(value[1]);
c.setProducts(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
c.showProducts();
}
}
Class Products
public class Product {
private String id;
private double price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(String p) {
double price = Double.parseDouble(p);
this.price = price;
}
}
I tried to use the parseDouble()
method to transform the attribute when it was set by the setPrice
method, but the following error occurred:
Exception in thread "main" java.lang.NumberFormatException: For input
string: ""price""
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Product.setPrice(Product.java:16)
at Catalog.main(Catalog.java:41)