Shaker
Shaker

Reputation: 1

Trying to read from text file using string.split

I'm trying to read through a text file so that i can find a book by name and then output its attributes, im getting wierd results. help?

This is the code:

                System.out.print( "Enter name of book: " );
                input2 = scanner.nextLine();
                this.setName(input2);
                String bookName = getInfo.readLine();
                int i = 0, num = 0;

                while(bookName != null)
                {
                    String[] bookNames = bookName.split("|");
                    i++;
                    for(int j = (i*4-4); j<(i*4); j++)
                    {
                        if (bookNames[j] == this.name){
                            num = 1; 
                        }
                    }
                    if(num == 1){
                        System.out.println(bookName);
                        num = 0;
                    }
                    bookName = getInfo.readLine();
                }

This is the file :

candy mang|doodle|4586|45.0|

cradle|Michael|1111|1.0|

This is the output:

Press 1 to add a book, and 2 to find a book.

2

How would you like to search for the book?

1

Enter name of book: candy mang

c

a

n

d

l

e

|

Exit?

c

Upvotes: 0

Views: 89

Answers (3)

ring bearer
ring bearer

Reputation: 20783

| in regular expression is used as an alternator(OR). So splitting with "|" is same as splitting with "" which means split each character. That's the reason you have multiple character output. Escape the special symbol as "\\|"

Observation :

Do not compare two objects using == as you have done bookNames[j] == this.name. Instead use bookNames[j].equals(this.name);

Upvotes: 0

Codebender
Codebender

Reputation: 14471

| is a special character in regex. So you will need to escape it.

String[] bookNames = bookName.split("\\|"); // Not the 2 backslashes.

Upvotes: 0

William Moore
William Moore

Reputation: 3994

It looks like your trying to read a CSV file where a pipe (|) is the delimiter. Why not just use a CSV library like: http://opencsv.sourceforge.net/

You can then set the delimiter using:

     CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '|');

You can then read the file line by line searching for your desired book:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '|');
 String [] nextLine;
 while ((nextLine = reader.readNext()) != null)
 {
    // nextLine[] is an array of values from the line
    if(nextLine[0] == desiredBookName)
    {
        // Output desired attributes
    }
 }

Upvotes: 1

Related Questions