In this example, if you enter text, it will be transferred in pieces with the output. How to make the typed text remain in place when outputting from a stream.

import java.util.Scanner; class testThread implements Runnable{ @Override public void run() { for(int i=0;i<1000;i++){ System.out.println("LOG message"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class test { public static void main(String[] args) { Scanner in = new Scanner(System.in); new Thread(new testThread()).start(); while (true){ String str = in.nextLine(); System.out.println(str); } } } 

Closed due to the fact that the essence of the issue is incomprehensible by the participants Yuriy SPb

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    Try to formulate a different question. The essence of your problem is not clear at the moment - YuriySPb

1 answer 1

In your case, there is no way; the message LOG message will be added after the text you entered.

You need to add the following event handler: if you have entered something, then wait until then. until they hit enter . you need to cache the log and collect messages

response to the comment below The KeyListener interface KeyListener to catch everything.

 @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == 13) // enter code isPresed = true; else { isPresed = false; System.out.println("not enter"); } @Override public void run() { StringBuilder sb = new StringBuilder(); for(int i=0;i<1000;i++){ if(!isPresed) { System.out.println(sb.toString()); System.err.println("LOG message"); sb = new StringBuilder(); } else sb.append("LOG message\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } 
  • How to determine that something is entered and have not yet pressed enter? - croll
  • @croll updated the answer - Senior Pomidor
  • I understand that KeyListener only works with the GUI. And with the console what to think? - croll