Need Help How to take use input through BufferedReader

When i m taking Integer input from bufferedReader its giving numberFormat Exception

Hi, @kushoz

In Java, java.io.BufferedReader is a very efficient way of reading a file, but it doesn’t provide a built-in way to get the next integer, long, etc. Since you’re often required to do that for CodeChef problems, you would need to use additional tools.

The common way that I know of is to read a line of input at a time using readLine(), then break it into tokens using StringTokenizer, then parse each token. Here is some sample code (untested):

   class MyReader {
      BufferedReader reader;
      StringTokenizer currentTokens;
      public MyReader(BufferedReader readerToReadFrom) {
         this.reader = readerToReadFrom;
         this.currentTokens = new StringTokenizer(readNextLine());
      }

      public String nextToken() {
         while (!currentTokens.hasMoreTokens()) {
            String line = readNextLine();
            // If end of file reached, throw an exception
            if (line == null) throw new RuntimeException("End of file reached while parsing");
            currentTokens = new StringTokenizer(line);
         }
         return currentTokens.nextToken();
      }

      private String readNextLine() {
         try {  // try-catch block required to handle IOException
            return reader.readLine();
         } catch (IOException e) {
            throw new RuntimeException(e);
         }
      }
   }

With that class and a properly created BufferedReader called bufferedReader, the following code works:

MyReader myReader = new MyReader(bufferedReader);
String firstToken = myReader.nextToken();
int firstInt = Integer.parseInt(firstToken); // assuming first token int the file is an integer

Alternatively, you can just stick with java.util.Scanner to read your input. Although it is relatively slow, it is fast enough for most early-level problems you encounter, and it doesn’t require the extra supporting code shown above.

Congratulations on solving HIT earlier today, by the way.

Cheers!

1 Like

Thank You So Much :slight_smile::blush::sweat_smile: