Search code examples
javaiochar

JAVA char input


My code is not taking input into a char variable after it takes its first value.

import java.io.*;
import java.lang.Character;
public class Test
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));                                                                                          
        char s;
        for(int i=0;i<3;i++)
        {
            System.out.print("->");
            s=(char)br.read();
            System.out.print(s);
        }
    }
}

I am getting this output

->a
->>

And i wont this

->a
a
->b
b
->c
c

Solution

  • According to Java Docs: Here

    read() function reads a single character at a time.

    Input Provided : a followed by Enter.

    br.read() reads following characters in iteration: a -> \r -> \n in the first three iterations. If you loop over for more than 3, it would again prompt for user input.

    You can approach your problem by following two ways:

    1. Using read() function : In this case, input needs to be like 'abcd' instead of 'a', then 'b', then 'c' then 'd'.
    
        public static void main(String args[])throws IOException
               {
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));                                                                                          
                   char s;
                   for(int i=0;i<3;i++)
                   {
                       System.out.print("->");
                       s=(char)br.read();
                       System.out.print(s);
                   }
               }
    
    1. Using readLine() function: Input would be the way mentioned in question.
    public static void main(String args[])throws IOException
                {
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));                                                                                          
                    String s;
                    for(int i=0;i<3;i++)
                    {
                        System.out.print("->");
                        s=br.readLine();
                        System.out.print(s);
                    }
                }