0

I'm trying to read an object called Word that has a char array as attribute. I'm trying to read words from a text file (.txt), but i have a problem only with the first word. When i use my method it reads a character thats not in the word (i think its a new line or something)

Here's my method

public void read(BufferedReader f) {
    numCaracteres=0;

        while ((caracter != ' ')) {
            caracteres[numCaracteres]=caracter;
            numCaracteres++;
            caracter=(char) f.read();
        }
    }catch (Exception e) {
        System.err.println(e);
    }

PS: After i write a word in the file, i separate it with the next using a blank space

Holger
  • 285,553
  • 42
  • 434
  • 765
  • did you checked the encoding of your file? maybe BOM problem. http://en.wikipedia.org/wiki/Byte_order_mark – pms Aug 20 '14 at 16:52
  • 1
    "*When i use my method it reads a character thats not in the word*" how is that possible? This method will not even compile because of (1) wrong `{` `}` placement, (2) lack of `try` before `catch` block. – Pshemo Aug 20 '14 at 16:52
  • http://stackoverflow.com/questions/17405165/first-character-of-the-reading-from-the-text-file-ï – Jaqen H'ghar Aug 20 '14 at 16:54
  • You are `read`ing *after* you store the character into the array. That must fail for the first iteration of the loop. – Holger Aug 20 '14 at 16:54
  • What is the default `caracter`? Also I assume that should have been `character`. – Elliott Frisch Aug 20 '14 at 16:56
  • Why don't you use java.util.Scanner? This will do all the white space skipping for you. – laune Aug 20 '14 at 17:00
  • A char array is an unwieldy way for storing character strings. – laune Aug 20 '14 at 17:06

1 Answers1

0

Throw away read and use:

Scanner scn = new Scanner( someBufferedReader );
while( scn.hasNext() ){
    String word = scn.next();
    // process word
}
laune
  • 31,114
  • 3
  • 29
  • 42