Ankit Khare
Ankit Khare

Reputation: 1385

Taking input through console Java

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

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?

Upvotes: 0

Views: 86

Answers (2)

Ahmad Alfawwaz Timehin
Ahmad Alfawwaz Timehin

Reputation: 303

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.

Upvotes: 0

C. Helling
C. Helling

Reputation: 1402

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.

Upvotes: 1

Related Questions