Search code examples
javaparsingnumberformatexception

Input data: java.lang.NumberFormatException: For input string: "2 "


Here is my data from the text file:

21/08/12#ESE-6329#PV/5732#30
27/08/12#PEA-4567#PV/5732#3@
11/09/12#ESE-5577#Xk/8536#2
14/09/12#PNW-1235#HY/7195#2@

And this is a code form the main method:

File orderData = new File("PurchaseOrderData.txt");            
Scanner dataScan = new Scanner(orderData);

while(dataScan.hasNextLine())
{
    String lineData = dataScan.nextLine();

    Scanner lineScan = new Scanner(lineData);
    lineScan.useDelimiter("#");

    String date = lineScan.next(); // line 259
    String id = lineScan.next();
    String code = lineScan.next();

    String quantityPlus = lineScan.next();

    if(!quantityPlus.contains("@"))
        management.addNewPurchaseOrder(date, id, code, 
                                    Integer.parseInt(quantityPlus)); // line 267
    else
    {
        quantityPlus = quantityPlus.replace("@", "");
        management.addNewPurchaseOrder(date, id, code,
                                    Integer.parseInt(quantityPlus));
        management.startNewMonth();
    }

On the first instance of

management.addNewPurchaseOrder(date, id, code, Integer.parseInt(quantityPlus));

I get this exception:

java.lang.NumberFormatException: For input string: "2 "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Assignment2.MainTest.main(MainTest.java:267)

If I do:

String quantityPlus = lineScan.next();
quantityPlus = quantityPlus.replace(" ", "");

I get the following:

java.util.NoSuchElementException
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at Assignment2.MainTest.main(MainTest.java:259)

MainTest.java:259 - String date = lineScan.next();

I've tried to use nextInt() as well, but the result is the same. What is wrong there?

Thanks a lot!


Solution

  • MainTest.java:259 - String date = lineScan.next(); You should check before if the line is not empty this might be why the scanner is throwing an exception