dimanche 18 octobre 2020

Second class not resetting when testing from another class

I have a class ("TestProject") that is supposed to print the output of another class to the console, each time using a different input text file (e.g. "input01.txt", "input02.txt").

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class TestProject {
    public static void main(String[] args) throws IOException {
        for(int inputNumber = 2; inputNumber <= 7; inputNumber++) {

            String[] arguments = new String[] {"input" + String.format("%02d", inputNumber) + ".txt", "1"};
            
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream newPS = new PrintStream(baos);
            PrintStream oldPS = System.out;
            
            System.setOut(newPS);
            
            Project.main(arguments);
            
            System.out.flush();
            System.setOut(oldPS);
            
            newPS.close();
            
            System.out.println(baos.toString());
        }
    }
}

This works correctly for the first input file, as seen below:

arguments:  "input02.txt" 0
1, 3, 80.5, 20, 60, 0, Stone, 0, 0
2, 3, 80.5, 20, 60, 0, Flame, 2, 2

1, 4, 80.0, 20, 60, 0, Stone, 0, 1
2, 4, 80.0, 20, 60, 0, Flame, 2, 2

1, 5, 79.5, 20, 60, 0, Stone, 0, 2
2, 5, 79.5, 20, 60, 0, Flame, 2, 2

1, 6, 79.0, 20, 60, 0, Stone, 1, 1
2, 6, 79.0, 20, 60, 0, Flame, 2, 2

But after this, every subsequent test prints only the final output of the first test:

arguments:  "input03.txt" 0
1, 6, 79.0, 20, 60, 0, Stone, 1, 1
2, 6, 79.0, 20, 60, 0, Flame, 2, 2


arguments:  "input04.txt" 0
1, 6, 79.0, 20, 60, 0, Stone, 1, 1
2, 6, 79.0, 20, 60, 0, Flame, 2, 2


arguments:  "input05.txt" 0
1, 6, 79.0, 20, 60, 0, Stone, 1, 1
2, 6, 79.0, 20, 60, 0, Flame, 2, 2


arguments:  "input06.txt" 0
1, 6, 79.0, 20, 60, 0, Stone, 1, 1
2, 6, 79.0, 20, 60, 0, Flame, 2, 2


arguments:  "input07.txt" 0
1, 6, 79.0, 20, 60, 0, Stone, 1, 1
2, 6, 79.0, 20, 60, 0, Flame, 2, 2

I thought that this might have something to do with calling the main() method of another class multiple times, but nothing online seems to suggest that this is an issue. When running the main program separately, the output works fine for all input files. This leads me to think that the problem exists in this short excerpt.

Thanks in advance, to all.

Aucun commentaire:

Enregistrer un commentaire