I am trying to print out a message based on whether or not a previous specific message was printed. Here is my code:
public class Main {
public static Runnable getRunnable() {
return () -> {
System.out.println("Hello from a thread");
};
}
public static void main(String[] args){
new Thread(getRunnable()).start();
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
if (name.equals("Hello from a thread")) {
System.out.println("Hi!");
} else {
System.out.println("That's not nice");
}
}
}
I know that Scanner is probably no the solution here, but whenever I try something else like System.console.readLine()
, which is probably also not correct, it prints out a NullPointerException
. What am I supposed to use here to read previous output?
UPDATE: Hey, I tried it again but it didn't work out... not sure why again. Here's my updated code
public static ByteArrayOutputStream baos = new ByteArrayOutputStream();
public static PrintStream ps = new PrintStream(baos);
public static PrintStream old = System.out;
public static Runnable getRunnable() {
System.out.println("Hello from a thread");
return () -> {
System.setOut(ps);
System.out.println("Hello from a thread");
};
}
public static void main(String[] args){
new Thread(getRunnable()).start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
System.out.println("Somethings wrong!");
}
System.out.flush();
System.setOut(old);
if (baos.toString().equals("Hello from a thread")) {
System.out.println("Hello other thread!");
}
}
}