Reputation: 299
Trying to read int from file. My problem is that my code read all the integers in the first line, but on the succeeding line it skips the first number. To illustrate my file has these numbers: 1, 4, 6, 7, 8, 11, 9, 1, 4, 6, 7, 8, 11, 12, 2, 4, 6, 7, 11, 12, 0,
but when i use the code below it only prints 1 4 6 7 8 11 9 then 4 6 7 8 11 12 then 2... it skips the first no.
Scanner file = null;
ArrayList<Integer> listtwo = new ArrayList<>();
try {
file = new Scanner(new File(filename+".txt")).useDelimiter(",| ");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(file.hasNext()){
if (file.hasNextInt()){
listtwo.add(file.nextInt());
}
file.next();
}
for (Integer i: listtwo) System.out.println(i);
Upvotes: 0
Views: 1631
Reputation: 85
You need to change
while(file.hasNext()){
if (file.hasNextInt()){
listtwo.add(file.nextInt());
}
file.next();
}
to EDIT
int i = 0;
while(file.hasNextInt()){
listtwo[i++] = file.nextInt();
}
In your code, it is first searching for the next "word" in the text file. The "if" statement then tells it to find the next int after that first "word", thus it skips the first number of the line.
Upvotes: 1
Reputation: 1777
Use like this file.next(); will run twise if you have file.hasNextInt() is true to avoid that use else case.
while(file.hasNext()){
if (file.hasNextInt()){
listtwo.add(file.nextInt());
}else{
file.next();
}
}
Upvotes: 0