1

EDIT: Sorted. See bottom for solution

Okay, I have to write a program that takes in user inputs until the user types "x", at which time my code is supposed to evaluate three things:

  1. if number of inputs (n) is square
  2. if inputs are unique & contain numbers 1-n
  3. if the order in which the inputs were put in generates a magic square.

Everything I'm posting compiles, and I can "x" or "(char)" on the first input, but if I enter an integer, I get:

Exception in thread "main" java.lang.NullPointerException at Square.add(Square.java:32) at TestMagicSquare.main(TestMagicSquare.java:40)

What am I doing wrong?? Here's my code. (Ignore the sum checking methods, I have yet to flesh them out.)

FUNCTIONAL CLASS

    /*
    *   HW 01
    *   Nick Smith
    *   1 December 2011
    *   
    */

    import java.util.*;

    public class Square
    {
private ArrayList<Integer> numbers;
private int [][] square;
private int rowSum, colSum, TLBRSum, TRBLSum = 0;

/*
*   Default constructor of Square class
*   
*/
public Square ()
{

}   

//step 0 add inputs to arraylist numbers
/*
*
*
*/
public void add(int i)
{
    numbers.add(i);
}

//step 1 after inputs, number of inputs are square
/*
*
*
*/
public boolean isSquare()
{
    for(int i=0; i<50; i++)
    {
        if(numbers.size() == i*i)
        {
            return true;
        }
    }
    return false;
}

//step 2 after inputs, check if all unique #s are used
/*
*
*
*/
public boolean isUnique()
{
    for(int i = 1; i<=numbers.size(); i++)
    {
        if(numbers.contains(i))
        {
            return true;
        }
    }
    return false;
}

//step 3 populate indices in numbers into square

/*
*
*
*/
public void addToSquare()
{
    for(int i=0; i<square.length; i++)
    {
        for(int j=0; j<square[0].length; j++)
        {
            square[i][j] = numbers.get(i*square.length+j);
        }
    }


}

//step 4 find the magic number

/*
*
*
*/
public int findMagicNumber()
{
    int magicNumber = 0;

    for(int i=0; i < square.length; i++)
    {
        magicNumber += square[0][i];
    }

    return magicNumber;
}

/*
*
*
*/
public int addRows()
{

    return rowSum;
}

/*
*
*
*/
public int addCols()
{
    return colSum;
}

/*
*
*
*/
public int addTLBR()
{
    return TLBRSum;
}

/*
*
*
*/
public int addTRBL()
{
    return TRBLSum;
}

//step 5, check if rows = cols = diagonals = magic number
/*
*
*
*/
public boolean isMagic()
{
    if (addRows() == addCols() && addTLBR() == addTRBL() && addRows() == addTRBL() && addRows() == findMagicNumber())
    {
        return true;
    }
    return false;
}

}

TEST CLASS

    import java.util.*;

    public class TestMagicSquare
    {
public static void main (String [] args)
{

    //instantiate new Scanner class object
    Scanner scan = new Scanner(System.in);

    //instantiate new Square class object from default constructor
    Square mySquare = new Square();

    //instance variables
    boolean running = true;
    String prompt = ".  Enter a number (x to quit): ";
    String error = "***Invalid data entry, please try again.***";
    int inputNum = 1;

    //Allow user to input until "x" is typed
    while(running)
    {
        System.out.print("\nInput number " + inputNum + prompt);

        if(!scan.hasNextInt())
        {
            if(scan.next().equalsIgnoreCase("x"))
            {
                System.out.println("Input terminated by user.  Checking for square and magicness.");
                running = false;
            }
            else
            {
                System.out.println(error);
            }
        } 
        else
        {
            inputNum++;
            mySquare.add(scan.nextInt());
        }
    }

    //Note for Dec 6 - Compiles, but not sure if this logic is right.

    //  Test inputs against constraints defined in functional class Square
    if(!mySquare.isSquare())
    {
        System.out.println("Step 1: Number of inputs not square.  Aborting program");
    }
    else if(!mySquare.isUnique())
    {
        System.out.println("Step 2: Numbers are not unique.  Aborting program.");
    }
    else if(!mySquare.isMagic())
    {
        System.out.println("Step 3: Square is not magic.  Aborting program.");
    }
    else
    {
        System.out.println("Step 1: Number of inputs is square");
        System.out.println("Step 2: Numbers are unique");
        System.out.println("Step 3: MAGIC SQUARE!  Holy crap!");
    }
}
   }

As always, any help is appreciated.

SOLUTION:

Thanks, everyone. I've all but got it now. I really appreciate your help.

I used

    private ArrayList<Integer> numbers = new ArrayList();

in the top declarations along with

    private int [][] square;

and

    double dubble = Math.sqrt(numbers.size());
    int squareSize = (int)dubble;

    square = new int[squareSize][squareSize];

in the AddToSquare() method, which I called directly after my while loop in the test class.

I hope this helps anyone looking for the answer in the future.

novalsi
  • 71
  • 1
  • 11
  • Where do you intialize private ArrayList numbers ? – jatanp Dec 06 '11 at 06:51
  • 1
    " java.lang.NullPointerException at Square.add(Square.java:32) at ". Take a look at that line. Something is null there. – Thilo Dec 06 '11 at 06:51
  • @jatanp - I define it at the top, but is that not enough? Must I make a instantiate a new Arraylist? – novalsi Dec 06 '11 at 06:53
  • @Thilo - Sadly, I'm but a wee novice. I agree something is null, but I can't make heads or tails of what. – novalsi Dec 06 '11 at 06:54
  • @novalsi There is a difference between *declaring* something and *defining* it. You've only done the former. – Tomalak Dec 06 '11 at 06:58
  • @novalsi: If you have solved your problem then post an answer and accept it. Much better chance of helping others that way – musefan Dec 06 '11 at 09:15

2 Answers2

2

I think you missed to instantiate the ArrayList<Integer> and an array - private int [][] square;

private ArrayList<Integer> numbers=new ArrayList<Integer>();
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • Thank you, that seems to be working better. Still not perfectly, but there are other problems in the code (such as my apparently made-up array.add). – novalsi Dec 06 '11 at 07:01
1

You never said that there was a list of numbers.

private ArrayList numbers;

should probably be

private List numbers = new ArrayList();

Will Sargent
  • 4,346
  • 1
  • 31
  • 53