Skip to content
Advertisement

toString() representation output

I have a bug in the code and believe me I’ve run debugging many times to find what’s wrong with code but cannot understand what is wrong. I have to output the contents of 2d Arraylist. For example, if I do:

JavaScript

it outputs me the following:

JavaScript

But when I change the fourth value, 3, to higher number, for example, 4 ((-4,1,-2,4,"A")), then it says:

JavaScript

All of my constructors work well, and I assume the bug is in the toString() method. And again, I’ve tried to debug it several times but still cannot make my mind what can be wrong here. Could smb please help me? The error happens in this line inside toString() method:

Advertisement

Answer

You increase the row for each column:

JavaScript

This is also the reason why it works for #rows >= #columns but not for #rows < #columns

Extract myBoard.get(row++) as variable before inner for loop, like

JavaScript

and move

JavaScript

out of the outer loop.

Or, here is a suggestion with the whole class (please pay attention, I only improved the indexed access. There is enough room for further improvements, e.g string concatenations):

JavaScript

}

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement