Convert String from an array to Int - Java

Asked

Viewed 80 times

0

I have a.csv file that has three information inside it, a name, a price and a quantity, needed to convert the amount that is in this file separated by "," to an Array and then pass as parameter in a list, only that generates an error.

public static void main(String[] args) {
    Scanner sc = new Scanner (System.in);
    String path = "E:\\Temp\\ws-eclipse\\ProjectFile\\sourcefile.csv";
    List<Fileswork> list = new ArrayList();
    
    try (BufferedReader bfReader = new BufferedReader(new FileReader(path))){
            String line;
            while((line = bfReader.readLine()) != null){
                String []itens = line.split(",");
                
                String Name = itens[0].trim();
                double Price = Double.valueOf(itens[1].trim());
                int Quantity = Integer.parseInt(itens[2].trim());

                list.add(new Fileswork(Name, Quantity, Price));
            }
            
            for(Fileswork var : list) {
                System.out.println(var.getQuantity());
            }
            bfReader.close();
    }

Exception in thread "main" java.lang.NumberFormatException: For input string: "1""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Application.Program.main(Program.java:26)

Citação

  • At first it seems to be because in the record there are not only numbers, there are quotes at the end (1"). If you can [Dit] the question by adding some lines of the CSV (mainly the one that generates the error), you can be more sure (and we can detect other possible errors)

  • I put the excerpt from the file that is in CSV, but it does not have this ( 1 ").

  • 2

    Please do not put this information as image (read the FAQ to understand the reason), and yes as text. Anyway, I suggest you open the file in a text editor (can be even in the same Notepad). It is common that Excel and other similar programs save CSV with quotes, especially if they are fields configured as text (but these quotes do not appear when vc opens in the spreadsheet itself)

  • Thank you, solved my problem, did not know about this issue of programs affect the text put there.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.