以前の特定のメッセージが印刷されたかどうかに基づいてメッセージを印刷しようとしています。私はスキャナがここでおそらく解決策ではありません知っているが、私はまた、おそらく正しいではありませんSystem.console.readLine()
のような何かを、してみてくださいたび、それはNullPointerException
をプリントアウト過去の印刷物からコンソールを読み取ろうとしていますJava
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");
}
}
}
:ここに私のコードです。以前の出力を読み込むためにここで何を使用するのですか?
更新:もう一度やり直してみましたが、うまくいきませんでした。理由はわかりません。ここに私の更新されたコード
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!");
}
}
}
おそらくこれがあなたを助けるかもしれません。https://stackoverflow.com/questions/8708342/redirect-console-output-to-string-in-java –