1
I am reading data from an external file with CSV format. However this data is coming in CSV format String
. There is a price field that I need to turn into double
for handling 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 method parseDouble()
to transform the attribute when set by the method setPrice
, 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)
The format of the data in the file is like this:
"4357590126397428","R$ 629.99"
, the first column beingid
and the second isprice
. I couldn’t use the methodreplace
to remove characters (including quotes are coming together).– Diego Soares