Reputation: 58
I was practicing using Scanner and I've encountered an strange occurance and i would like some help from the community to understand this. I've a text file with the following numbers
1,2,3,9
5,9
3
reading the text file with the following java code
fsc = new Scanner(new File(fileName));
fsc.useDelimiter(",");
while (fsc.hasNextLine()) {
while (fsc.hasNextInt()){
System.out.print(fsc.nextInt() + ",");
}
System.out.println();
fsc.nextLine();
}
and the results always skips the last number.
1,2,3,
5,
3,
How do i make it not ignore the last item?
Edit: Some solutions calls for splinting them to an array and converting the strings to integer however I would like to explore using Scanner.nextInt()
instead
Edited 2: I'm so sorry seems many misunderstood the question. What i meant was missing is the last digit of each line is missing!
Upvotes: 1
Views: 486
Reputation: 688
This is because you removed the standard delimiters, i.e. linefeeds. You need
fsc.useDelimiter("[ ,\r\n]");
So this becomes
fsc = new Scanner(new File(fileName));
fsc.useDelimiter("[ ,\r\n]");
while (fsc.hasNextLine()) {
while (fsc.hasNextInt()){
System.out.print(fsc.nextInt() + ",");
}
System.out.println();
if (fsc.hasNextLine())
fsc.nextLine();
}
Upvotes: 3