1

I am trying to parse through this csv file. In the second column which consist of ItemId's contains integers, however some contain an 'X' at the end. I am trying to remove the character and output a new csv file. However it appears my conditional statement

if (itemId.charAt(itemId.length()-1) == 'X') 

isn't being satisfied.

CODE:

Scanner console = new Scanner(new File("data/BX-Book-Ratings.csv"));
PrintStream output = new PrintStream(new File("data/Book-Ratings.csv"));
String row;

String itemId;


while(console.hasNextLine())
{
    row = console.nextLine();
    Scanner inputRow = new Scanner(row).useDelimiter(";");
    output.print(inputRow.next() + ","); //userid


    itemId = inputRow.next();
    if (itemId.charAt(itemId.length()-1) == 'X') {
        itemId = itemId.substring(0, itemId.length() - 1);
    }

    long newitemId = Long.parseLong(itemId);
    output.print(newitemId + ",");      //itemid
    output.println(inputRow.next());    //rating 

}

DATA:

"276725";"034545104X";"0"
"276726";"0155061224";"5"
"276727";"0446520802";"0"
"276729";"052165615X";"3"
"276729";"0521795028";"6"
"276733";"2080674722";"0"
"276736";"3257224281";"8"
"276737";"0600570967";"6"
"276744";"038550120X";"7"
"276745";"342310538";"10"
"276746";"0425115801";"0"
"276746";"0449006522";"0"
0

1 Answer 1

2

You code currently ignores the quotes. You need to handle them too, though:

itemId = inputRow.next();
if (itemId.charAt(itemId.length() - 2) == 'X') {
    // Remember the end quote ------^

    itemId = itemId.substring(1, itemId.length() - 2);
    // Get rid of the quotes -^  and the X --------^
} 
else {
    itemId = itemId.substring(1, itemId.length() - 1);
    // Get rid of the quotes -^--------------------^
}

long newitemId = Long.parseLong(itemId);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.