0

Hi and happy new year everyone!

I'm working with a csv file which looks like this:

orange | red blue | green red | red brown | brown yellow | black grey | pink 

My goal is scanning every row and check if each pair is made of the same item or not.

I'd like to print the total number of rows having different items.

In this case we have 4.

And I'd like also to print which row contains them, with its respective number.

In this case:

1 orange red 2 blue green 5 yellow black 6 grey pink 

I've searched for similar questions here, but all I could find was about multiple csv files.

I'm using Java... from what I've understood so far, a good start would be:

Scanner scanner = new Scanner(new File("path to my csv file")); scanner.useDelimiter(";"); while(scanner.hasNext()){ // comparing items in rows } scanner.close(); 

I don't know what to do in the while loop now.

Many thanks!

5
  • Read the file line by line. For each line, split the line using the pipe separator. Check if the two elements of the line are equal or not. I don't really understand why using a scanner with ; as the delimiter would help reading lines and splitting them using the | separator. Commented Jan 1, 2017 at 12:12
  • There is no pipe actually! It was just to show the two columns Commented Jan 1, 2017 at 12:12
  • Then use ; to split each line. Commented Jan 1, 2017 at 12:13
  • What is your actual delimiter? Given the above comments, this is not clear. Commented Jan 1, 2017 at 12:14
  • Sorry for my unclear explanation. My delimiter is ; Commented Jan 1, 2017 at 12:16

1 Answer 1

2

The implementation below should work, under the assumption that each line's two items are separated by semicolon with optional whitespace. If this be not the case, then you can change the delimiter used for splitting each line.

int total = 0; int rowNum = 1; while (scanner.hasNext()) { // comparing items in rows String[] parts = scanner.nextLine().split("\\s*;\\s*"); if (!parts[0].equals(parts[1])) { System.out.println(rowNum + " " + parts[0] + " " + parts[1]); ++total; } ++rowNum; } System.out.println("There were " + total + " rows where the two items were not equal."); 
Sign up to request clarification or add additional context in comments.

5 Comments

It works as expected, thanks. Just one question: does scanner.useDelimiter(";"); become useless in this case?
@NoobNe0 Whitespace is part of the default delimiter, but AFAIK if you specify a custom delimiter then whitespace is no longer default. Hence, I gave the above answer.
Thanks for the clarification.
@NoobNe0 One more point: If you are sure that your CSV file only has a semicolon, and nothing else, as a delimiter, then setting the delimiter this way should be no problem.
I'll try that too then!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.