bucky bucky - 5 months ago 30
Java Question

Printing 2d array with markers set by coordinates on Java

I have a basic question, which is literally driving me mad.
I have a method which is gets a list of some objects as a parameter. Every object has a pair of ints (for x and y coordinates respectivly).
The goal is: print the 2d array with markers set for every object in the list at given coordinates, like example below (m-is a marker; array size is h:2, w:5). Array width and high must stay intact.


Here's one of solutions I've come to. Its main issue that array width is multiplied with the amount of objects in the parameter list.

Assumption: Array is a char array and predefined. Named 't'.

public void printArray (ArrayList<Marker> marker) {
for (int h=0;h<t.length;h++) {
for (int w=0;w<t[h].length;w++) {
for (Marker m: marker) {
if (h==m.getY() && w==m.getX()) {
} else {

Please, give me a clue how to fight this.


It is quite obvious why this happens of course: for each coordinate you print a character for each marker. This is solved by getting rid of the loops on h and w.

This can for example be done something like this:

public void printArray (ArrayList<Marker> marker) {

    // Create an array of chars, and make sure all values are set to '.'
    boolean[][] array = new char[t.length][t[h].length];
    for (int h=0; h < t.length; h++) {
        for (int w=0; w < t[h].length; w++) {
            array[h][w] = '.';

    // For each marker, set the value in the array at the marker's position to m
    for (Marker m: marker) {
        array[m.getY()][m.getX()] = 'm';

    // Print the array
    for (int h=0; h<t.length; h++) {
        for (int w=0; w<t[h].length; w++) {

Probably this is not the optimal solution, because there is a lot of looping. I don't know if java has a better method for initializing the array values, for example.