Why my code doesn't work? I can't see where it might be wrong :/
package com.codegym.task.task19.task1927;
/*
Contextual advertising
*/
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class Solution {
public static TestString testString = new TestString();
public static void main(String[] args) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream newps = new PrintStream(baos);
System.setOut(newps);
testString.printSomething();
System.setOut(System.out);
String[] lines = baos.toString().split("\\n");
for (int i = 0; i < lines.length; i++) {
System.out.println(lines[i]);
if (i % 2 != 0) {
System.out.println("CodeGym - online Java courses");
}
}
}
public static class TestString {
public void printSomething() {
System.out.println("first");
System.out.println("second");
System.out.println("third");
System.out.println("fourth");
System.out.println("fifth");
}
}
}
System.out
is a static final variable. Because of being final you can not set it directly. For that the System class has the static methodsetOut(PrintStream)
. I hope you can see where this is going. In line 17 you setSystem.out
tonewps
. And that's why reverting to the initial value like won't work.System.out
effectively references herenewps
. What you need to do is to backup the original reference of System.out, like and then use that backup variable to restore the originalSystem.out
variable.