Search code examples
javacharuser-inputbufferedreader

Run time error occurred when trying to take input using buffered reader and char


I am a newbie in java, this is my following code to take input from the user to add two number.

package additio;

import java.io.*;
public class Additio
{
public static void main(String args[])throws Exception
{


BufferedReader br= new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter the two numbers to add:");
char d=(char) br.read();
char e=(char) br.read();
int a=Character.getNumericValue(d); 

int b=Character.getNumericValue(e); 
int c = a+b;
System.out.println("\nSum of two numbers:"+c);
}
}

Now, my questions are:-

It only takes one input instead of writing the code for taking two input, why this runtime error has occurred

and why it takes only single value that is it only takes value o to 9 which means it only takes ones value, providing tens value it only gives 1 which is the runtime error.


Solution

  • If you are wondering why your code is not taking two inputs its because br.read() does not differentiate between a carriage return(enter key) and a valid input. It does not recognize the return key as end of the input stream and considers the enter as the second input. To work around this , add a br.readLine() like so ,

    char d=(char) br.read();
    br.readLine();
    char e=(char) br.read();
    

    This will consume the new line and still be available to take the next input