Quick actions

cmd+k|ctrl+k

Navigation

Languages

Exceptions are dumb

Snippet info

Language

Java

Visibility

public

Author

vortai

Created

2016-05-15T12:40:46Z

Updated

2016-05-15T13:07:32Z

/**
 * This class models one square on the 2048 board.
 * A square can be empty, denoted by 0; 
 * or it can hold a tile with a number in {2,4,8,16,32,64,...}. 
 * 
 * @author Lyndon While
 * @version 1.0
 */

public class Square
{
    public static void main(String[] args) {
        Square sqr1 = new Square(32);
        System.out.println(sqr1.getSquare());
    }
    
    private int x; // the value of the tile sitting on the square, or 0 for empty

    // create a square with the value x, or empty if x is not legal 
    public Square(int x)
    {
        try
        {
            setSquare(x);
        }catch (Exception e)
        {
            System.out.println(e);
        }
    }

    // return the current value of the square 
    public int getSquare()
    {
        return x;
    }
    
    // return true iff the square is empty
    public boolean isEmpty()
    {
        return x == 0;
    }
    
    // put a tile of value x on the square, if x is legal; 
    // otherwise throw an Exception with a suitable error message 
    public void setSquare(int x) throws Exception
    {
        if ((x & (x - 1)) == 0)
        {
            this.x = x;
        }
        else
        {
            throw new Exception("Not valid input");
        }
    }
}
INFO