0

I participate in programming competitions a lot and the most important part of that is taking input from user for that we generally use two things

  • BufferedReader
  • Scanner

Now the problem is sometimes each of the above while taking input gives following errors 1. Nullpointer exception 2. NoSuchElementFoundException

Below is the code for both

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());

Scanner is

Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

Can anyone explain why this is happening so?

2 Answers 2

1

Well, in one case, your BufferedReader is null, so br.readLine() results in a NullPointerException.

Similarly, you can't call sc.nextInt() if there is no such next element, resulting in a NoSuchElementException.

Solution: wrap it in a try/catch block.

Sign up to request clarification or add additional context in comments.

3 Comments

Also, br.readLine() can return a null if the stream is already closed. Both of those classes and the behavior of their methods are well documented in the API docs (docs.oracle.com/javase/7/docs/api)
But when I'm providing the input myself then how could this be null?
As @Gus said, perhaps the stream was closed. This is more of a question you ask yourself as you work through an example with a debugger.
0

Given the possible exceptions you could do something as simple as

try
{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n=Integer.parseInt(br.readLine());
}
catch(NullPointerException nullPE)
{
    //do Whatever it is that you want to do in case of the buffered reader being null.
}
catch (NumberFormatException numFE)
{
        //do Whatever it is that you want to do in case of a number format exception, probably request for a correct input from the user
}

Note that the reader is reading an entire line from the console so you must also catch a NumberFormatException.

In your other case, you can simple use a solution similar to the one provided below

try
{
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
}
catch(NoSuchElementException ex)
{
    //do Whatever it is that you want to do if an int was not entered, probably request for a correct input from the user
}

It is good practice to use Exception Handling to manage situations in your program that is based on arbitrary input from your users.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.