简体   繁体   中英

Java: BufferedReader lines compared to String issues

I have a program that is reading a text file that has a list of items, creates an ArrayList consisting of the items it reads, then compares it to a few chosen words. For example, my text file contains this (without the numbering):

  1. book
  2. desk
  3. food
  4. phone
  5. suit

and it reads each one and adds it to an ArrayList. When I tried comparing a String s = "book" to each element in the ArrayList, I find that s is not equal to anything. This is what I have in a method:

for (int i = 0; i < list.size(); i++)
{
if (s.equals(list.get(i))
    return true;
}

s.contains() doesn't work either. When I print the ArrayList, there's an additional whitespace at the end of each String element. How can I get the comparison to work when s = "book"? Why is there additional whitespace?

You can use the trim() method of the String class to remove whitespaces in the start and the end of the string.

The whitespaces may be in the file but you didn't notice it. Check with an editor that there are no spaces at the end. To be more sure, check with a hexadecimal editor like hd on unix.

Also, check that the read strings do not contain the line feed character.

Use trim() to remove leading and trailing whitespace.

if (s.equals(list.get(i).trim())
    return true;
}

instead of

if (s.equals(list.get(i))
  return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM