I want to read the numbers from the following text file:
5
8
-2
11
3
-5
2
10
This is my java code:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inStream = null;
ArrayList<Integer> arrayList = new ArrayList<>();
try {
String userInput = bufferedReader.readLine();
inStream = new FileInputStream(userInput);
BufferedReader readerFile = new BufferedReader(new InputStreamReader(inStream));
while(readerFile.ready()) {
// System.out.println(Integer.parseInt(readerFile.readLine()));
int number = Integer.parseInt(readerFile.readLine());
arrayList.add(number);
}
System.out.println("Foreach print:");
for(int number:arrayList) {
System.out.println(number);
}
}
catch (Exception e) {
System.out.print(e.getClass().getSimpleName());
}
finally {
bufferedReader.close();
inStream.close();
}
}
}
Like this the code works perfectly.
What I don`t understand is when I use the line System.out.println(Integer.parseInt(readerFile.readLine()));
as part of my code in order to see what he reads. The rest remains unchanged. I get this result:
Why do I get this result? I`m totally confused. Thx in advance!
Greetings from Vienna/Austria
Fabian
Every time you call readerFile.readLine() it reads one line. So when you uncomment the line you have commented, then half the lines are being eaten by that code and half are being eaten by the line after it.
while(readerFile.ready()) {
String line = readerFile.readLine();
System.out.println(Integer.parseInt(line));
int number = Integer.parseInt(line);
arrayList.add(number);
}
would fix it. Or better still:
while(readerFile.ready()) {
int number = Integer.parseInt(readerFile.readLine());
System.out.println(number);
arrayList.add(number);
}