I do not think this version of the code prints "Hello".
You call:
int line = in.read();
What does it do? Take a look in Javadocs on Reader :
public int read ()
throws an IOException
Reads one character . This method will block until a character is available, an I / O error occurs, or the end of the stream.
(my accent)
Your code reads "H" from "Hello", which is 72 in ASCII.
Then it goes into your loop with line == 72, so it goes into the loop:
for(int i=0;i<line;i++)
... making the decision "is 0 less than 72? Yes, so I will go into the loop cycle."
Then, each time he reads a character, the line value changes to another integer, and each time cycle approaches i . So the loop says: "Continue moving until the ASCII character value is greater than the number of iterations I counted."
... and every time he goes, he prints this character on a separate line.
As it happens, for your input it reads the end of the file (-1), and as -1 < i the loop continuation condition is not fulfilled.
But for longer inputs, it stops at the first "a" after the 97th character or in the first "b" after the 98th character, etc. (since ASCII "a" is 97, etc.)
H e l l o J a v a
This is not what you want:
- You do not want your loop to repeat until I> = "the character I just read." You want it to repeat until
in.read() returns -1 . You were probably taught to quote until the condition is met. - You do not want
println() each character, as this adds new lines that you do not need. Use print() .
You should also look at the Reader.read(byte[] buffer) method Reader.read(byte[] buffer) and see if you can write code to work in large chunks.
Two patterns that you will use over and over in your programming career:
Type x = getSomehow(); while(someCondition(x)) { doSomethingWith(x); x = getSomehow(); }
... and ...
Type x = value_of_x_which_meets_condition; while(someCondition(x)) { x = getSomehow(); doSomethingWith(x); }
See if you can build something with FileReader and the value that you get from it by filling out somehows.