user
user

Reputation: 914

Parsing through csv file

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"

Upvotes: 1

Views: 67

Answers (1)

Mureinik
Mureinik

Reputation: 311163

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);

Upvotes: 2

Related Questions