Tack
Tack

Reputation: 121

Reading file of unspaced integers – hasNextInt() never returns true

I'm trying to read a list of unspaced integers from a file and I can't figure out why I never get past the conditional in my while loop.

This is the entire "nums.txt" file:

12121212121212121212121212121212
00001212121212121212121212121212
33331212121212121212121212121212

And the little script looks like this:

import java.util.Scanner;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class Test{
  public static void main(String[] args){
    try{
      Scanner reader = new Scanner(new BufferedReader(new FileReader(new File("nums.txt"))));
      while(reader.hasNextInt()){
        System.out.println(reader.nextInt());
      }
     reader.close()
    }
    catch(FileNotFoundException e){
        e.printStackTrace();
    }
  }
}

When run, this outputs nothing, and terminates.

Upvotes: 0

Views: 714

Answers (3)

Tack
Tack

Reputation: 121

A functional solution to this issue, by reading chars and returning the values as they are in the file:

  BufferedReader reader = new BufferedReader(new FileReader(new File("nums.txt")));
    while(reader.read()%48 != -1){
      System.out.println(reader.read()%48);
    }

Because the file could contain newlines and other characters, one would need to do additional parsing to accept only the desired numbers as they are returned.

Or using Scanner:

  Scanner reader = new Scanner(new File("nums.txt"));
    while(reader.hasNextLine())
    for (String token : reader.nextLine().split("(?!^)"))
        System.out.println(token);

Upvotes: 0

slim
slim

Reputation: 41261

According to its JavaDoc Scanner.hasNextInt():

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.

12121212121212121212121212121212 is the next token, and it can't be interpreted as an int, because the maximum int is 2147483647.

Therefore hasNextInt() returns false, and your loop ends.

A Scanner by its nature works on tokens split by a delimiter (by default, space). If you want to consume one char at a time use Reader.read() or even InputStream.read().

Upvotes: 3

mba12
mba12

Reputation: 2792

Something like this should work for you. Be sure to do something with each int that gets generated or you'll loose it.

BufferedReaderreader = new new BufferedReader(new FileReader(new File("nums.txt")));

while ((currentChar = br.read()) != null) {
    // discard white space
    if (!java.lang.Character.isWhitespace(currentChar))
            int x = Integer.parseInt(currentChar)
            // do something with the int
}

Upvotes: 0

Related Questions