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?

JudyJiang
  • 2,017
  • 5
  • 21
  • 45
  • 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. – JudyJiang Apr 01 '14 at 21:41

1 Answers1

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);   
            }
         }
      }
   }
}
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346