1

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!");
    }

}

}

Ryan Koo
  • 53
  • 7

1 Answers1

1

System.out is not System.in

System.out is the standard output stream, which usually prints to console. System.in is the standard input stream, which usually is taken from console. You can do setOut, setIn, and setErr to change the I/O streams, so for your case, you would need to redirect in to read from a source and out to output to that source. You may consider using an ArrayList to store and retrieve the output / input:

final List<Integer> list = new ArrayList<>();
System.setOut(new PrintStream(new OutputStream() {
    public void write(int b) {
        list.add(b);
    }
}));
System.setIn(new InputStream() {
    public int read() {
        if (list.size() == 0) return -1;
        return list.remove(0);
    }
});

(Note that for various reasons, you probably want to do setErr so you can still output things properly.)

You can try a working example of this here

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50