Search code examples
javaarraysprintstream

PrintStream Arrays


I am trying to make a method that takes int[][] list and filename String outName as parameters, reads each list[i][j] entry and converts them to ascii character accordingly.

This is what I have:

public static void makeAscii(int[][] list, String outName) {
    try {
    PrintStream output = new PrintStream(new File(outName));
    for (int i = 0; i<list.length; i++) {
        for (int j = 0; j<list[0].length; j++){
        if (list[i][j] <= 20 && list[i][j] >= 0) {
            System.out.print('M');
        }
        if (list[i][j] <= 21 && list[i][j] >= 40) {
            output.print('L');
        }
        if (list[i][j] <= 41 && list[i][j] >= 60) {
            output.print('I');
        }
        if (list[i][j] <= 61 && list[i][j] >= 80) {
            output.print('o');
        }
        if (list[i][j] <= 81 && list[i][j] >= 100) {
            output.print('|');
        }
        if (list[i][j] <= 101 && list[i][j] >= 120) {
            output.print('=');
        }
        if (list[i][j] <= 121 && list[i][j] >= 140) {
            output.print('*');
        }
        if (list[i][j] <= 141 && list[i][j] >= 160) {
            output.print(':');
        }
        if (list[i][j] <= 161 && list[i][j] >= 180) {
            output.print('-');
        }
        if (list[i][j] <= 181 && list[i][j] >= 200) {
            output.print(',');
        }
        if (list[i][j] <= 201 && list[i][j] >= 220) {
            output.print('.');
        }
        if (list[i][j] <= 221 && list[i][j] >= 255) {
            output.print(' ');
        }
        }
        System.out.println();
    }
    }
    catch (FileNotFoundException e) {
        System.out.println("Coudln't create file");
        System.exit(-1);
    }

}

The problem that I have is that while this method creates a txt file accordingly, it does not write any characters in the text-file, thus leaving the file blank. Why is this?


Solution

  • You have inverted the conditions in your ifs.

    Take the first one:

    if (list[i][j] <= 21 && list[i][j] >= 40) {
    

    This means that it will be true when there is a number that is both less than 21 and greater than 40. Obviously, this can't happen. You need to invert the condition to:

    if (list[i][j] <= 40 && list[i][j] >= 21) {
    

    The same goes for the rest of your ifs.

    Also, note that you need to close your PrintStream at the end of the method. A good practice would be to wrap it with a try-with-resources statement.