Brian Jones Brian Jones - 3 months ago 13
Java Question

using Scanner and next() with println error

import java.util.Scanner;

import static java.lang.Thread.sleep;

class RunnableDemo implements Runnable {
private Thread t;
private String threadName;

RunnableDemo( String name){
threadName = name;
}
public void run() {
System.out.println("asd");
}

public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

}

class RunnableDemo1 implements Runnable {
private Thread t;
private String threadName;

RunnableDemo1( String name){
threadName = name;
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Enter here:");
String x = in.nextLine();
System.out.println(x);
}

public void start ()
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

}


public class Main {

public static void main(String[] args) throws InterruptedException {
RunnableDemo1 R1 = new RunnableDemo1( "Thread-1");
R1.start();
sleep(1000);
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();


}
}


Println will print a line to the command prompt but in.nexLine() (also tried in.next() does not recognize it. Is there any way I am able to print a string to the command prompt and have the scanner recognize it? Or something similar?

Answer

System.out.println shouldn't send anything to the server since it sends the String to the standard out only, usually the console, unless you've re-routed the standard out, something that I don't recommend that you do. Instead you need to actually send something to the server, perhaps in your notifyObservers method, but hard to say without your mcve.

In all this remains a very incomplete question until you improve it.

Edit: yes the Observable API shows that public void notifyObservers(Object arg) has an overload that accepts an Object parameter. Why not pass your String in there?


Edit 2: OK, you're confused, because that's not how you have one class communicate with another. Printing something out to the console will not trigger the System.in to update in another thread. Again, do what I stated above.