1

I want to read a String in a char array without using any of String class function, not even charAt(), lenght() in Java. I know one method char c=(char) System.in.read(). But in this, the user char write a whole sentence on command Line even for inputting a single char. I want that user will be able to type one character and then i can do some operations on it, then the next character on the same line....(as we do in c++) . Please give me some suggetstions. I want a code working similar like in c++

// c++ code
char c, d[50];
cin.get(c); 
int i=0;
while(c != '\n')
{
    d[i++]=c;
    ...           //any expressions
    ...
    cin.get(c); 
}
satya
  • 23
  • 6
  • 2
    First hint to avoid annoying Java programmers: it's Java, not JAVA. – Jon Skeet Jul 29 '14 at 09:08
  • 3
    Your C++ code is flawed. `i` is not initialised. – user657267 Jul 29 '14 at 09:08
  • 2
    And why do you want it to be done, as java simplifies it with String methods – Santhosh Jul 29 '14 at 09:08
  • 6
    It sounds like what you're *really* asking for is: "Can I read a character from the console without waiting for a line break" - which has very little to do with "reading a string in character array without using any string function" – Jon Skeet Jul 29 '14 at 09:09
  • Are you also asking that the user inputs a `char` and perform some operation WHILE waiting for another char? I.E multithreading? – qbit Jul 29 '14 at 09:30
  • yes i want to read a character from console without waiting for a line break. – satya Jul 29 '14 at 09:38
  • i also wanted to know methods of reading a string in character array without using any string function. I was asked to perform in an Interview, where i have to reverse all words in a sentence without using string class and any string function and also the number of words in a string should be odd. – satya Jul 29 '14 at 09:42
  • Well regarding the reversing, would something like that do? `System.out.println(new StringBuilder("abc").reverse());` – qbit Jul 29 '14 at 10:12
  • thanx, but they told me not to use any inbuilt functions similar to String class. I have to work at character levels only and i had to create my own functions, thats why i am asking. – satya Jul 29 '14 at 10:26

1 Answers1

0

There's no easy way to handle one character at a time.

See on SO this and this. You may work around this problem with some headaches and on particular OSes and no data from System.in but rather from your own structures. If you find a way to flush System.in at each keystroke, your problem is solved. As far as I know, you can't register a keyboard IRQ from Java.

Your no-String requirement is the easy part, as you may use the same structure as you would in C++. The problem is the mechanism behind cin.get() which has no analogue in Java.

Community
  • 1
  • 1
webuster
  • 2,410
  • 13
  • 25