As far as reading characters into the array is concerned, you don't actually put them into the array so your array is not used.
Joanne Neal wrote:
Richard Tookey wrote:As far as reading characters into the array is concerned, you don't actually put them into the array so your array is not used.
Yes he does. On line 10. That also explains why he is only losing the first character and not alternative characters.
:-) Yep - my mistake! Since he reads a character in the while() I made the assumption he read a character at a time in the body of the loop. Silly of me. This does not change the fact that the character read in the while is discarded without being used.
Mansukhdeep Thind wrote:Where is the first character going Jo?
Assigned to an integer and returned - therefore being compared with an integer. From the java docs, on what is returned:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached
Mansukhdeep Thind wrote:So, how do I ensure that I read the first character also?
This does not change the fact that the character read in the while is discarded without being used.
You need to asign it to a variable in the which statement. It's not obvious how to do this so I'll show you just this once
If you want to read the characters into an array in one go, that's a bit more complicated, so I'll leave that as an exercise for you.
Mansukhdeep Thind wrote:What was preventing the earlier code from reading the first character?
The earlier code was reading the first character, but because you didn't assign the read value to any variable it was discarded as soon as the comparison to -1 had been done. You then read all the remaining characters (or at least up to 1024 of them) into the array.
In the code provided by Joanne the value returned by read() is assigned to a char variable which is then compared to -1, so the while loop executes once for each char until the end of the stream is found. If you change your code to only read one char at a time inside the while loop you will see it only prints out every other char. This is because after reading the char and printing it out the while statement would execute again and read the next char and and execute the while loop until the end of stream is found. Of course if there is an odd number of chars in the stream the last print out will print the end of stream marker.