Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6898967
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T07:21:45+00:00 2026-05-27T07:21:45+00:00

EDIT: Sorted. See bottom for solution Okay, I have to write a program that

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T07:21:46+00:00Added an answer on May 27, 2026 at 7:21 am

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

    private ArrayList<Integer> numbers=new ArrayList<Integer>();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Edit: I have solved this by myself. See my answer below I have set
Edit: From another question I provided an answer that has links to a lot
EDIT: This was formerly more explicitly titled: - Best solution to stop Kontiki's KHOST.EXE
EDIT: Learned that Webmethods actually uses NLST, not LIST, if that matters Our business
I know that __builtin__ sorted() function works on any iterable. But can someone explain
I have a 2D-array that I want to sort based on the second column.
I have a combobox on my form that is bound to a generic list
I have this little problem I couldn't find in Google: UITableView works fine until
I have a fairly large, sophisticated algorithm that uses a std::priority_queue . In some
I have a find function that locates a string in a JTable with quite

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.