Magic Square NullPointerException。好极了

时间:2011-12-06 06:48:36

标签: java nullpointerexception

编辑:排序。请参阅底部了解解决方案

好的,我必须编写一个程序,接受用户输入,直到用户键入“x”,此时我的代码应该评估三件事:

  1. 如果输入数量(n)是正方形
  2. 如果输入是唯一的&包含数字1-n
  3. 如果放入输入的顺序会产生幻方。
  4. 我发布的所有内容都会编译,我可以在第一个输入中“x”或“(char)”,但如果我输入一个整数,我会得到:

      

    线程“main”java.lang.NullPointerException中的异常     在Square.add(Square.java:32)     在TestMagicSquare.main(TestMagicSquare.java:40)

    我做错了什么?这是我的代码。 (忽略总和检查方法,我还没有把它们充实。)

    功能类

        /*
        *   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!");
        }
    }
       }
    

    与往常一样,任何帮助都表示赞赏。

    解决方案:

    谢谢大家。我现在都得到了它。我非常感谢你的帮助。

    我用过

        private ArrayList<Integer> numbers = new ArrayList();
    
    顶部声明中的

        private int [][] square;
    

        double dubble = Math.sqrt(numbers.size());
        int squareSize = (int)dubble;
    
        square = new int[squareSize][squareSize];
    

    在AddToSquare()方法中,我在测试类中的while循环后直接调用。

    我希望这有助于将来寻找答案的任何人。

2 个答案:

答案 0 :(得分:2)

我认为您错过了实例化ArrayList<Integer>和数组 - private int [][] square;

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

答案 1 :(得分:1)

你从未说过有一个数字列表。

私人ArrayList号码;

应该是

private List numbers = new ArrayList();