0

I'm trying to write a java program to handle continuous type in, character by character. Basically, it means, there's a string variable "input" to record the current typed in string. So, if the current type in is "W", than input should be "W" and the user keeps type in "h" the input should be "Wh" and so on.

I want it to be character by character, I think it should be some while loop using scanner?

OK. I can do it string by string. but when does the Scanner stops? I tried:

while(in.hasNext()){ String temp = in.next(); if(temp.equals("")){ break; } }

But the Scanner didn't stop. The loop didn't stop. What's the input value of java from the "Enter Return" Key? Do I need to import the keyboard listener?

1
  • I tried while(in.hasNext()) in which in is a Scanner type. But it doesn't work properly. My point is as user typing in "What is.." The input variable will change dynamically instead of finish the whole read period. Commented Apr 1, 2014 at 21:41

1 Answer 1

1

No, a Scanner won't work since it only accepts the String after ENTER has been pressed. You will either need a non-standard console or create a Swing GUI, use a JTextField that has a DocumentListener added to it.


Edit
For @tieTYT He gave a link to this answer which recommends use of Console to solve this problem. Putting his code in a small program:

import java.io.Console;
import java.io.IOException;

public class Test {
   public static void main(String[] args) throws IOException {
      Console cons = System.console();
      if (cons == null) {
         System.out.println("Console is null");
         System.exit(-1);
      } else {
         System.out.println("Enter text, or \"z\" to exit:");
         while (true) {
            char c = (char) cons.reader().read();
            System.out.println("" + c);
            if (c == 'z') {
               System.exit(0);   
            }
         }
      }
   }
}
Sign up to request clarification or add additional context in comments.

4 Comments

No it just seemed promising. When I tried it, the first line returned null.
@tieTYT: I have just now tested it, and can verify that it does not work. That the Console only gets the chars when enter has been pressed. I'll post my code above.
This is becoming a side conversation, but any idea on why it returned null for me? I ran in JDK 6 in Intellij IDEA
@tieTYT: it's null likely because you're running it inside of Intellij. It's null if I run it in Eclipse, but not if I run it from the command line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.