简体   繁体   中英

Why can't I read a int value after char value in Java?

I have created a simple Java application using readLine() of BufferedReader . The code is as follows:

import java.io.*;
class demo_data
{
    public static void main(String hh[])throws Exception
    {
        char c=' ';
        int i=0;
        String name="";
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter char:");
        c=(char)br.read();
        System.out.print("Enter String:");
        name=br.readLine();
        System.out.print("Enter value:");
        i=Integer.parseInt(br.readLine());
        System.out.print("\tChar:"+c+"\tName:"+name+"\tValue:"+i);
    }
}

My problem is that after reading character value, the string statement is skipped and I'm not able to read the value for variable name. If I read a char value and then try to read int value it throws a NumberFormatException . Why?

BufferedReader#read() , reads a single character from your input. It does not read the linefeed at the end of the input.

So, your linefeed goes as input to the br.readLine you have after your br.read . Now, if you enter a string for the 2nd br.readLine , it is actually goind to the 3rd one. And hence that Exception.

So, your name variable will contain a linefeed - \\n , and the string which you passed for name goes to your int i .

Workaround: -

Try adding an empty br.readLine after br.read() to consume the left over linfeed: -

c=(char)br.read();
br.readLine();  // Add an empty `br.readLine here.
System.out.print("Enter String:");
name=br.readLine();

Or, you can also go with @Peter's answer below

The call to readLine() immediately returns because of the newLine that will still be in the buffer after you entered the first char .

Add an extra br.readLine() to fix this:

    System.out.print("Enter char:");
    c=(char)br.read();
    br.readLine();
    System.out.print("Enter String:");
    name=br.readLine();

You have to read extra line after reading char c=(char)br.read(); because its Reads a single character.

    System.out.print("Enter char:");
    c=(char)br.read();
    br.readLine();
    System.out.print("Enter String:");
    name=br.readLine();
    System.out.print("Enter value:");
    i=Integer.parseInt(br.readLine());
    System.out.print("\tChar:"+c+"\tName:"+name+"\tValue:"+i);

In each case you are really reading a line at a time not just one character and one number.

    System.out.print("Enter char:");
    char c = br.readLine().charAt(0);
    System.out.print("Enter String:");
    String name = br.readLine();
    System.out.print("Enter value:");
    int i = Integer.parseInt(br.readLine());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM