Программа NullPointerException LifeGame.java

1

Я работаю над этим довольно долгое время и не могу понять, почему я получаю сообщение об ошибке Исключение в потоке "main" java.lang.NullPointerException в LifeGame.cellValue(LifeGame.java:91) в Life.main(Life.java: 31)

после ввода имени файла каждый раз, когда я его запускаю.

Это основной файл. Life.java

 import java.util.*;  // Scanner
 import java.io.*;    // PrintStream


 public class Life {

    static PrintStream theScreen = new PrintStream(System.out);
    static Scanner theKeyboard = new Scanner(System.in);

    public static void main( String args[]) {

            theScreen.print("\nEnter the name of the initial configuration file: ");
            String inFile, str;
            inFile = theKeyboard.nextLine();

            // initialize the game
            LifeGame theGame = new LifeGame(inFile);


            int count = 0;
            while(true)
        {
                    // display current configuration
                theScreen.println(theGame.cellValue(0, 0));
                theScreen.println("\nGeneration " + count
                            + " - press 'Enter' for the next "
+ "generation or type 'done' to finish");
                    str = theKeyboard.nextLine();

                    if (str.equals("done")) break;

                    // generate next configuration
                    theGame.nextGeneration();
                    count++;
        }
    }
 }

Это LifeGame.java

 import java.util.*; // Scanner
 import java.io.*;  // File

 public class LifeGame 
 {

    // define private variables here
int myRows=0;
int myCols=0;
int[][] myGrid;
static PrintStream theScreen = new PrintStream(System.out);

    // ++++++++++++++++++++++++++++++++++++++++++++++++++
    // * LifeGame constructor.                          *
    // * Receive: fileName, a string.                   *
    // * Precondition: fileName contains the name of    *
    // *   a file containing a Life configuration       *
    // *   (the number of rows, the number of columns,  *
    // *    and the values of each cell).               *
    // * Postcondition: myGrid has been initialized     *
    // *    to the configuration in fileName.           *
    // ++++++++++++++++++++++++++++++++++++++++++++++++++

    public LifeGame(String fileName)
    {
        Scanner theFile = null;


            try
            {
                theFile = new Scanner(new File(fileName));
            }
            catch (FileNotFoundException e)
            {
                System.err.println("File Not Found");
                System.exit(1);
            }
            myRows = theFile.nextInt();
            myCols = theFile.nextInt();
            int[][] myGrid = new int[myRows][myCols];
            for (int i = 0; i < myRows; i++)
                {
                    for (int j = 0; j < myCols; j++)
                        {
                            int num = theFile.nextInt();
                            myGrid[i][j] = num;
                        }
                }
            theFile.close();
            System.out.println(myRows+" "+myCols);
    }

    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // * LifeGame columns extractor.                        *
    // * Return: the number of columns in my configuration. *
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++

    public int columns()
    {
        return myCols;
    }

    // ++++++++++++++++++++++++++++++++++++++++++++++++++*
    // * LifeGame rows extractor.                        *
    // * Return: the number of rows in my configuration. *
    // ++++++++++++++++++++++++++++++++++++++++++++++++++*

    public int rows()
    {
        return myRows;
    }

    // ++++++++++++++++++++++++++++++++++++++++++++++++++*
    // * LifeGame cell Value extractor.                  *
    // * Return: the value in cell [row][col]            *
    // ++++++++++++++++++++++++++++++++++++++++++++++++++*

    public int cellValue(int row,int col)
    {
        for (int i = 0; i < rows(); i++)
        {
            for(int j = 0; j < columns(); j++)
                {
                    if (myGrid[i][j] == '1')
                    {
                        theScreen.println("* ");
                    }
                    else
                    {
                        theScreen.println("  ");
                    }
                }
        System.out.println();
        }

    return 0;
    }

    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // * Mutator to generate next LifeGame generation.      *
    // * Postcondition: For each cell myGrid[r][c]:         *
    // *   if myGrid[r][c] had 3 living neighbors:          *
    // *     myGrid[r][c] contains a 1.                     *
    // *   if myGrid[r][c] had less than 2 neighbors OR     *
    // *       myGrid[r][c] had more than 3 neighbors:      *
    // *     myGrid[r][c] contains a 0.                     *
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++

    public void nextGeneration()
    {
        int neighbors = 0;
        int tempGrid[][] = myGrid;
        for (int r = 0; r < myRows; r++)
            {
            for (int c = 0; c < myCols; c++)
                {
                 neighbors = (tempGrid[r-1][c-1]
                 + tempGrid[r-1][c]
                 + tempGrid[r-1][c+1]
                 + tempGrid[r][c-1]
                 + tempGrid[r][c+1]
                 + tempGrid[r+1][c-1]
                 + tempGrid[r+1][c]
                 + tempGrid[r+1][c+1]);
                 if ( neighbors == 3)
                     {
                    myGrid[r][c] = 1;
                     }
                 else if ( neighbors < 2 || neighbors > 3)
                    myGrid[r][c] = 0;

                }
            }
    }



    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // * LifeGame toString function member.                 *
    // * override the toString method to display the array  *
    // * Return: a String containing my configuration.      *
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++
    public String toString()
    {
        return "";
    }

 } // end of the class

И это файл, который читается в

test.life

 5 5\n
 0 0 0 0 0\n
 0 0 1 0 0\n
 0 0 1 0 0\n
 0 0 1 0 0\n
 0 0 0 0 0\n
Теги:
exception
nullpointerexception

3 ответа

4
Лучший ответ

Проблема заключается в том, что myGrid имеет значение null. Если вы посмотрите на LifeGame() вы заметите, что переопределяете локальную версию myGrid чтобы вы не myGrid переменную-член правильно.

Изменить:

int[][] myGrid = new int[myRows][myCols];

Для того, чтобы:

myGrid = new int[myRows][myCols];
1

По линии 40 в LifeGame.java у вас есть:

int[][] myGrid = new int[myRows][myCols];

Если вы пытаетесь создать экземпляр переменной myGrid вместо локального myGrid, тогда вы должны снять int [] []

myGrid = new int[myRows][myCols];

Поскольку вы никогда не создаете экземпляр переменной экземпляра, он имеет значение null, когда вы вызываете его позже в функции cellValue().

1

MyGrid, вероятно, имеет значение null. Вы инициализируете что-то, называемое myGrid в своем конструкторе (только в конструкторе), но не self.myGrid (что для класса)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню