1

Is there any way of processing only single charater in java using a simple program?

I should ask user to enter a charater, when user enters a character my java program should process it before user enters the next character, and should give an immediate response to user on the character that he has entered.I tried this

public class InputChar {
    public static void main(String args[]) {
        System.out.printf("Enter Char ==> ");
        try {
            char temp = (char) System.in.read();

            System.out.printf("You Entered: " + temp + "\n");
        } catch (Exception exe) {
            exe.printStackTrace();
        }
    }
}

but still in above program whenever user enters a character it is not printing the character right away.In the above program when user presses 'Enter' key then only the program processes whatever he has entered.Is there anyway to do without pressing 'Enter' key to process the only first charater input that user has entered.

User 4.5.5
  • 1,311
  • 3
  • 12
  • 20
  • 1
    Have you searched? http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it. It's the second result on google for "console without enter java" – cklab Jun 28 '12 at 05:59
  • I think what you looking for is [Key Listener](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html). But unfortunately I don't know if this Listener can work in console. Are you trying to make like `auto-complete` function? – Crazenezz Jun 28 '12 at 06:34
  • I have already searched that question but could not come out with a simple java function which accepts a character from user like getch() in C language – User 4.5.5 Jun 28 '12 at 07:01
  • I'm not looking for a keyListner, i just want to process character entered by user after running the program on console without user explicitly pressing 'Enter' Key – User 4.5.5 Jun 28 '12 at 07:03

2 Answers2

1

First System.in.read() gets the input from the user. This allows the user to enter any number of characters.

Then you are converting it to char. So it takes the first character alone.

When you press enter only the input will be taken into process.

So that when you press enter key the next line is processed.

Though if you want to have still that "Enter key process", do apply some conditions when you get input from the user

Kalpana Raman
  • 51
  • 2
  • 5
0

If the variable declared as char,it holds only one char. The remaining char will be discarded even if user enter.

I guess it is not possible in console.Please refer this link

Prathap
  • 717
  • 2
  • 8
  • 25