0

For fun, I'm making a 2048-style combine-and-display program. Every outer loop, it adds a 2 to the 0-index of an integer array list. In an inner for-loop, it checks to see if the value of the index is the same as the value of the index above it; if it is, it doubles the value of indexi+1 and removes index i.
The output works fine for the first several loops. However, once we get to the first 128, it still works, but the next time we get a 128, it doesn't combine those to become 256, it just leaves both 128's at the end of the array.
I think the problem has to do with the code no longer recognizing 128 as being equal to 128, because it skips out of that if-statement when it should go in to it, but I'm not sure.
It currently infinitely loops; adding user interaction and quit statements will come later.
Code


public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<Integer> intArray = new ArrayList();
        Boolean quit = false; 
        while (quit == false) {
            intArray.add(0, 2);
            for (int i=0; i<intArray.size();i++) {
                try {
                    if (intArray.get(i) ==  intArray.get(i+1)) {
                        intArray.set(i+1, (intArray.get(i)*2));
                        intArray.remove(i);
                    }
                }
                catch (IndexOutOfBoundsException e) {
                }
            }
            for (int a : intArray) {
                System.out.print(a + "  ");
            }
            System.out.println();
        }
    }
}

Output

4  16  16  32  64  128  
2  4  32  32  64  128  
4  4  64  64  128  
2  8  128  128  
4  8  128  128  
2  4  8  128  128  
4  4  8  128  128  
2  8  8  128  128  
4  16  128  128  

Notice that the two 64's combine to make the second 128, but then those 128's don't combine as they should.
Do integers stop comparing correctly after a certain size?

Quintis555
  • 659
  • 3
  • 11
  • 16
  • 1
    I don't know who closed this while I was answering, but I think it was inappropriately closed. There is NO Integer (capital I) wrapper in the questioner's code. How does one dispute an inappropriate closing? – Alan Jun 26 '21 at 19:22
  • 2
    The arraylist is made up of (capitol-I) Integers. Does that count? – Quintis555 Jun 26 '21 at 19:25
  • 1
    Thanks. I guess it does. Missed that. – Alan Jun 26 '21 at 19:39
  • 3
    You should not use == to compare Integer objects, but rather .equals(). Integer caches elements up to 127, so == works from 0 to 127, but then fails on 128, because the two objects are different, even though they appear the same. – NomadMaker Jun 26 '21 at 20:00

0 Answers0