Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: When I run my program, it says error: java.lang.NullPointerException

  1. #1
    Junior Member
    Join Date
    May 2013
    Location
    Tilburg
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question When I run my program, it says error: java.lang.NullPointerException

    I tried to write a program such as the game of life, but without the sourcecode of the game of life. Just with the things I learned so far.

    It is not quit clean, but when it works it is fine to me.

    Right now I receive an error with NullPointerException.

    This is my code:

     
     
     
    import java.util.*;
    import java.io.*;
     
    class GameOfLife{  // main class
      Field field = new Field();
      Scanner scanner;
      File source;
      String filename = "GameOfLifeInput.txt";
      char[] charArray;
     
      public static void main(String[]args){ // starts up program
        new GameOfLife().play();
      } // end of method
     
      void readInitial(String filename){ // reads input from file
        try{
          source = new File(filename);
          scanner = new Scanner(source);
          String line = null;
          int row = 0;
          int col = 0;
          LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
          lnr.skip(Long.MAX_VALUE);
          lnr.getLineNumber();
          Cell[][] cells = new Cell[lnr.getLineNumber()+2][];
     
          while (scanner.hasNext()){
            line = scanner.nextLine();
            char[] charArray = line.toCharArray();
            cells[row] = new Cell[charArray.length+2];
            for (Character c : charArray){
              Cell cell = new Cell();
              if (c == ' '){
                cell.setAlive(false);
              }else{
                cell.setAlive(true);
              }
              cells[row+1][col+1] = cell;                                                                                  // This is line 43
              ++col;
            }
          ++row;
          }
          field.setField(cells);
        }catch(FileNotFoundException e){
          System.out.println("Could not find or open file due to \n"+e);
        }catch (IOException e) {}
     
      } // end of method 
     
      void play(){ //Asks user for number of generations and execute those generations with brakes of 2 secs in between them
        try{ 
          int numberOfGenerations = 0;
          int i = 0;
          scanner = new Scanner(System.in);
          System.out.println("How many generations do you want to see?");
          numberOfGenerations = scanner.nextInt();
          readInitial(filename);
          for(i = 0; i < numberOfGenerations; i++){
            field.print();
            field.generationNextCalc();
          }
     
          Thread.sleep(2000);
        }catch(InterruptedException e){
        }
      }
    } // end of class
     
    class Field{
      int i, j;
      Cell[][] cells;
     
      void setField(Cell[][] cells){ // method which replaces the empty matrix with the matrix with values read from file
        this.cells = cells;
      }
     
      void drawLine(){ //method to draw lines
        String s = "+";
        for(int i = 1; i <= cells[0].length-1; i++){
          s+="--";
        }
        s+="+";
        System.out.println(s);
      } // end of method
     
      public void print(){ //method to print generations
        drawLine();
        for(int i = 1; i <= cells.length-1; i++){
          System.out.print("|");
          for(int j = 1; j <= cells[i].length-1; j++){
            if(cells[i][j].isAlive()){ 
              System.out.print("*");
            }else{
              System.out.print(" ");
            }
          }
          System.out.println("|");
        }
        drawLine();
     
      } // end of method
     
      int numNeighbours(int i, int j){ // method to count the number of neighbors
        int numNeighbours = 0;
     
        if(i>0){
          if(cells[i-1][j].alive = true){  // Not top
            numNeighbours++;
          }
        }
        if(i<cells[0].length){  // Not bottem
          if(cells[i+1][j].alive = true){
            numNeighbours++;
          }
        }
        if(j>0){  // Not left
          if(cells[i][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(j<cells.length){  // Not right
          if(cells[i][j+1].alive = true){
            numNeighbours++;
          }
        }
        if(i > 0 && j > 0){  // If cell isn't on the left border and top border
          if(cells[i-1][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(i > 0 && j < cells.length-1){  // If cell isn't on the right border and top border
          if(cells[i-1][j+1].alive = true){
            numNeighbours++;
          }
        }
        if(i < cells[0].length-1 && j > 0){  // If cell isn't on the bottem border and not on left border
          if(cells[i+1][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(i < cells[0].length-1 && j < cells.length-1){  // If the cell isn't on the right border and the bottem border
          if(cells[i+1][j+1].alive = true){
            numNeighbours++;
          }
        }
     
        return numNeighbours;
      } // end of method
     
      void generationNextCalc(){ // method to count the next generation
        Cell cell = new Cell();
     
        for (int i = 1; i < cells[0].length-1; i++){
          for (int j = 1; j < cells.length-1; j++){
            int numNeighbours = numNeighbours(i,j);
            if (numNeighbours < 2 || numNeighbours > 3){
              cell.setAlive(false);
            }else if (numNeighbours == 3){
                cell.setAlive(true);
            }
          }
        } 
     
        /*for (int j = 1; j < cells.length-1; j++){
          for (int i = 1; i < cells[0].length-1; i++){
            generation[i][j] = generationNext[i][j];
          }
        }*/
      } // end of method
     
    } // end of class
     
    class Cell{
      boolean alive = false;
      GameOfLife character = new GameOfLife();
     
      boolean isAlive(){
        return alive;   
      } // end of method
     
      void setAlive(boolean state){
        alive = state;
      } // end of method
     
    } // end of class

    This is my output:

    > run GameOfLife
    How many generations do you want to see?
    [DrJava Input Box user typed 2]
    java.lang.NullPointerException
    at GameOfLife.readInitial(GameOfLife.java:43)
    at GameOfLife.play(GameOfLife.java:62)
    at GameOfLife.main(GameOfLife.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:272)
    >

    How do I have to initialize it? I thought I already did!


  2. #2
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    Can you explain in details what happened when you wrote Cell[][] cells = new Cell[lnr.getLineNumber()+2][]; - in your opinion?

  3. #3
    Junior Member
    Join Date
    May 2013
    Location
    Tilburg
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    Quote Originally Posted by angstrem View Post
    Can you explain in details what happened when you wrote Cell[][] cells = new Cell[lnr.getLineNumber()+2][]; - in your opinion?
    It reads the file
    Then calculates the number of rows(lines)
    I added 2, because I want to make a border around it

  4. #4
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    I see the calculations. I mean, what is created after this operation? What object? What it consists of?

  5. #5
    Junior Member
    Join Date
    May 2013
    Location
    Tilburg
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    Quote Originally Posted by angstrem View Post
    I see the calculations. I mean, what is created after this operation? What object? What it consists of?
    My new code:

     
     
    import java.util.*;
    import java.io.*;
     
    class GameOfLife{  // main class
      Field field = new Field();
      Scanner scanner;
      File source;
      String filename = "GameOfLifeInput.txt";
      char[] charArray;
     
      public static void main(String[]args){ // starts up program
        new GameOfLife().play();
      } // end of method
     
      void readInitial(String filename){ // reads input from file
        try{
          source = new File(filename);
          scanner = new Scanner(source);
          String line = null;
          int row = 0;
          int col = 0;
          LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
          lnr.skip(Long.MAX_VALUE);
          lnr.getLineNumber();
          Cell[][] cells = new Cell[lnr.getLineNumber()+2][];
     
          while (scanner.hasNext()){
            line = scanner.nextLine();
            char[] charArray = line.toCharArray();
            cells[row] = new Cell[charArray.length+2];
            for (Character c : charArray){
              Cell cell = new Cell();
              if (c == ' '){
                cell.setAlive(false);
              }else{
                cell.setAlive(true);
              }
              cells[row][col] = cell;
              ++col;
            }
          ++row;
          col = 0;
          }
          field.setField(cells);
        }catch(FileNotFoundException e){
          System.out.println("Could not find or open file due to \n"+e);
        }catch (IOException e) {}
     
      } // end of method 
     
      void play(){ //Asks user for number of generations and execute those generations with brakes of 2 secs in between them
        try{ 
          int numberOfGenerations = 0;
          int i = 0;
          scanner = new Scanner(System.in);
          System.out.println("How many generations do you want to see?");
          numberOfGenerations = scanner.nextInt();
          readInitial(filename);
          for(i = 0; i < numberOfGenerations; i++){
            field.print();
            field.generationNextCalc();
          }
     
          Thread.sleep(2000);
        }catch(InterruptedException e){
        }
      }
    } // end of class
     
    class Field{
      int i, j;
      Cell[][] cells;
     
      void setField(Cell[][] cells){ // method which replaces the empty matrix with the matrix with values read from file
        this.cells = cells;
      }
     
      void drawLine(){ //method to draw lines
        String s = "+";
        for(int i = 1; i <= cells.length-1; i++){
          s+="--";
        }
        s+="+";
        System.out.println(s);
      } // end of method
     
      public void print(){ //method to print generations
        drawLine();
        for(int i = 1; i < cells.length-1; i++){
          System.out.print("|");
          for(int j = 1; j < cells[i].length-1; j++){
            if(cells[i][j].isAlive()){                                                                                              //This is line 97
              System.out.print("*");
            }else{
              System.out.print(" ");
            }
          }
          System.out.println("|");
        }
        drawLine();
     
      } // end of method
     
      int numNeighbours(int i, int j){ // method to count the number of neighbors
        int numNeighbours = 0;
     
        if(i>0){
          if(cells[i-1][j].alive = true){  // Not top
            numNeighbours++;
          }
        }
        if(i<cells[0].length){  // Not bottem
          if(cells[i+1][j].alive = true){
            numNeighbours++;
          }
        }
        if(j>0){  // Not left
          if(cells[i][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(j<cells.length){  // Not right
          if(cells[i][j+1].alive = true){
            numNeighbours++;
          }
        }
        if(i > 0 && j > 0){  // If cell isn't on the left border and top border
          if(cells[i-1][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(i > 0 && j < cells.length-1){  // If cell isn't on the right border and top border
          if(cells[i-1][j+1].alive = true){
            numNeighbours++;
          }
        }
        if(i < cells[0].length-1 && j > 0){  // If cell isn't on the bottem border and not on left border
          if(cells[i+1][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(i < cells[0].length-1 && j < cells.length-1){  // If the cell isn't on the right border and the bottem border
          if(cells[i+1][j+1].alive = true){
            numNeighbours++;
          }
        }
     
        return numNeighbours;
      } // end of method
     
      void generationNextCalc(){ // method to count the next generation
        Cell cell = new Cell();
     
        for (int i = 1; i < cells[0].length-1; i++){
          for (int j = 1; j < cells.length-1; j++){
            int numNeighbours = numNeighbours(i,j);
            if (numNeighbours < 2 || numNeighbours > 3){
              cell.setAlive(false);
            }else if (numNeighbours == 3){
                cell.setAlive(true);
            }
          }
        } 
     
        /*for (int j = 1; j < cells.length-1; j++){
          for (int i = 1; i < cells[0].length-1; i++){
            generation[i][j] = generationNext[i][j];
          }
        }*/
      } // end of method
     
    } // end of class
     
    class Cell{
      boolean alive = false;
      GameOfLife character = new GameOfLife();
     
      boolean isAlive(){
        return alive;   
      } // end of method
     
      void setAlive(boolean state){
        alive = state;
      } // end of method
     
    } // end of class

    The error I had is now gone, but there is a new error now at line 97

    My input file is a file with on the first line three spaces, on the second line one space, one '*' and one space, and on the third and last line again three spaces.

    The output should be a new matrix with a slightly different generation and also a border around it.

  6. #6
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    The very same NullPointerException, I guess, with the very same array. Java's multidimensional array is just an array of references to other arrays. So, if one dimension is initialized, that does not mean, that other dimensions are initialized.

  7. The Following User Says Thank You to angstrem For This Useful Post:

    ProgrammerNoobE (May 28th, 2013)

  8. #7
    Junior Member
    Join Date
    May 2013
    Location
    Tilburg
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    Quote Originally Posted by angstrem View Post
    The very same NullPointerException, I guess, with the very same array. Java's multidimensional array is just an array of references to other arrays. So, if one dimension is initialized, that does not mean, that other dimensions are initialized.
    Thank you again!

    I think I'm almost there, just have my doubts about the output

    My recent code:

     
    import java.util.*;
    import java.io.*;
     
    class GameOfLife{  // main class
      Field field = new Field();
      Scanner scanner;
      File source;
      String filename = "GameOfLifeInput.txt";
      char[] charArray;
     
      public static void main(String[]args){ // starts up program
        new GameOfLife().play();
      } // end of method
     
      void readInitial(String filename){ // reads input from file
        try{
          source = new File(filename);
          scanner = new Scanner(source);
          String line = null;
          int row = 0;
          int col = 0;
          LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
          lnr.skip(Long.MAX_VALUE);
          lnr.getLineNumber();
          Cell[][] cells = new Cell[lnr.getLineNumber()][];
     
          while (scanner.hasNext()){
            line = scanner.nextLine();
            char[] charArray = line.toCharArray();
            cells[row] = new Cell[charArray.length];
            for (Character c : charArray){
              Cell cell = new Cell();
              if (c == ' '){
                cell.setAlive(false);
              }else{
                cell.setAlive(true);
              }
              cells[row][col] = cell;
              ++col;
            }
          ++row;
          col = 0;
          }
          field.setField(cells);
        }catch(FileNotFoundException e){
          System.out.println("Could not find or open file due to \n"+e);
        }catch (IOException e) {}
     
      } // end of method 
     
      void play(){ //Asks user for number of generations and execute those generations with brakes of 2 secs in between them
        try{ 
          Thread.sleep(2000);
          int numberOfGenerations = 0;
          int i = 0;
          scanner = new Scanner(System.in);
          System.out.println("How many generations do you want to see?");
          numberOfGenerations = scanner.nextInt();
          readInitial(filename);
          for(i = 0; i < numberOfGenerations; i++){
            field.print();
            field.generationNextCalc();
          }
        }catch(InterruptedException e){
        }
      }
    } // end of class
     
    class Field{
      int i, j;
      Cell[][] cells;
     
      void setField(Cell[][] cells){ // method which replaces the empty matrix with the matrix with values read from file
        this.cells = cells;
      }
     
      void drawLine(){ //method to draw lines
        String s = "+";
        for(int i = 1; i < cells[0].length-1; i++){
          s+="--";
        }
        s+="+";
        System.out.println(s);
      } // end of method
     
      public void print(){ //method to print generations
        drawLine();
        for(int i = 1; i < cells.length-1; i++){
          System.out.print("|");
          for(int j = 1; j < cells[i].length-1; j++){
            if(cells[i][j].isAlive()){ 
              System.out.print("*");
            }else{
              System.out.print(" ");
            }
          }
          System.out.println("|");
        }
        drawLine();
     
      } // end of method
     
      int numNeighbours(int i, int j){ // method to count the number of neighbors
        int numNeighbours = 0;
        i=0;
        j=0;
     
        if(i>0){
          if(cells[i-1][j].alive = true){  // Not top
            numNeighbours++;
          }
        }
        if(i<cells[0].length){  // Not bottem
          if(cells[i+1][j].alive = true){
            numNeighbours++;
          }
        }
        if(j>0){  // Not left
          if(cells[i][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(j<cells.length){  // Not right
          if(cells[i][j+1].alive = true){
            numNeighbours++;
          }
        }
        if(i > 0 && j > 0){  // If cell isn't on the left border and top border
          if(cells[i-1][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(i > 0 && j < cells.length-1){  // If cell isn't on the right border and top border
          if(cells[i-1][j+1].alive = true){
            numNeighbours++;
          }
        }
        if(i < cells[0].length-1 && j > 0){  // If cell isn't on the bottem border and not on left border
          if(cells[i+1][j-1].alive = true){
            numNeighbours++;
          }
        }
        if(i < cells[0].length-1 && j < cells.length-1){  // If the cell isn't on the right border and the bottem border
          if(cells[i+1][j+1].alive = true){
            numNeighbours++;
          }
        }
     
        return numNeighbours;
      } // end of method
     
      void generationNextCalc(){ // method to count the next generation
        Cell cell = new Cell();
     
        for (int i = 1; i < cells[0].length-1; i++){
          for (int j = 1; j < cells.length-1; j++){
            int numNeighbours = numNeighbours(i,j);
            if (numNeighbours < 2 || numNeighbours > 3){
              cell.setAlive(false);
            }else if (numNeighbours == 3){
                cell.setAlive(true);
            }
          }
        } 
     
        /*for (int j = 1; j < cells.length-1; j++){
          for (int i = 1; i < cells[0].length-1; i++){
            generation[i][j] = generationNext[i][j];
          }
        }*/
      } // end of method
     
    } // end of class
     
    class Cell{
      boolean alive = false;
      GameOfLife character = new GameOfLife();
     
      boolean isAlive(){
        return alive;   
      } // end of method
     
      void setAlive(boolean state){
        alive = state;
      } // end of method
     
    } // end of class

    Input:


    ***
    *
    **


    *


    Output:

    > run GameOfLife
    How many generations do you want to see?
    [DrJava Input Box user typed 5]
    +------+
    |***|
    | *|
    |** |
    | |
    | |
    | |
    +------+
    +------+
    |***|
    | *|
    |** |
    | |
    | |
    | |
    +------+
    +------+
    |***|
    | *|
    |** |
    | |
    | |
    | |
    +------+
    +------+
    |***|
    | *|
    |** |
    | |
    | |
    | |
    +------+
    +------+
    |***|
    | *|
    |** |
    | |
    | |
    | |
    +------+

    What do you think?

  9. #8
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    Your generationNextCalc method. Try to trace the life of a cell (from the beginning of the method) throughout the loops. Then reason, what changed on your field.
    Also, your cells have only 2 states. You can use booleans to represent them in an array - that's more clean and less memory-consumptive.

  10. #9
    Junior Member
    Join Date
    May 2013
    Location
    Tilburg
    Posts
    26
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    Quote Originally Posted by angstrem View Post
    Your generationNextCalc method. Try to trace the life of a cell (from the beginning of the method) throughout the loops. Then reason, what changed on your field.
    Also, your cells have only 2 states. You can use booleans to represent them in an array - that's more clean and less memory-consumptive.
    To change it all to boolean takes to long. there is only one error left. an out of bounderies error, could you see it?

    code:
    import java.util.*;
    import java.io.*;
     
    class GameOfLife{  // main class
      Field field = new Field();
      Scanner scanner;
      File source;
      String filename = "GameOfLifeInput.txt";
      char[] charArray;
     
      public static void main(String[]args){ // starts up program
        new GameOfLife().play();
      } // end of method
     
      void readInitial(String filename){ // reads input from file
        try{
          source = new File(filename);
          scanner = new Scanner(source);
          String line = null;
          int row = 0;
          int col = 0;
          LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
          lnr.skip(Long.MAX_VALUE);
          lnr.getLineNumber();
          Cell[][] cells = new Cell[lnr.getLineNumber()][];
     
          while (scanner.hasNext()){
            line = scanner.nextLine();
            char[] charArray = line.toCharArray();
            cells[row] = new Cell[charArray.length];
            for (Character c : charArray){
              Cell cell = new Cell();
              if (c == ' '){
                cell.setAlive(false);
              }else if (c == '*'){
                cell.setAlive(true);
              }
              cells[row][col] = cell;
              ++col;
            }
          ++row;
          col = 0;
          field.setField(cells);
          }
          //field.setField(cells);
        }catch(FileNotFoundException e){
          System.out.println("Could not find or open file due to \n"+e);
        }catch (IOException e) {}
     
      } // end of method 
     
      void play(){ //Asks user for number of generations and execute those generations with brakes of 2 secs in between them
        try{
          int numberOfGenerations = 0;
          int i = 0;
          scanner = new Scanner(System.in);
          System.out.println("How many generations do you want to see?");
          numberOfGenerations = scanner.nextInt();
          readInitial(filename);
          for(i = 0; i < numberOfGenerations; i++){
            field.print();
            field.generationNextCalc();
            Thread.sleep(2000);
          }
        }catch(InterruptedException e){
        }
      }
    } // end of class
     
    class Field{
      int i, j;
      Cell[][] cells;
     
      void setField(Cell[][] cells){ // method which replaces the empty matrix with the matrix with values read from file
        this.cells = cells;
      }
     
      void drawLine(){ //method to draw lines
        String s = "+";
        for(int i = 1; i < cells[0].length-1; i++){
          s+="--";
        }
        s+="+";
        System.out.println(s);
      } // end of method
     
      public void print(){ //method to print generations
        drawLine();
        for(int i = 1; i < cells.length-1; i++){
          System.out.print("|");
          for(int j = 1; j < cells[i].length-1; j++){
            if(cells[i][j].isAlive()){ 
              System.out.print("*");
            }else{
              System.out.print(" ");
            }
          }
          System.out.println("|");
        }
        drawLine();
     
      } // end of method
     
      int numNeighbours(int i, int j){ // method to count the number of neighbors
        int result = 0;
     
        for(i = 0 ; i<cells[0].length ; i++){
          for(j = 0 ; j<cells.length ; j++){
     
        if(i>0 /*&& j>0 && j<cells.length-1*/){
          if(cells[i-1][j].alive = true){  // Not top and not left and not right
            result++;
          }
        }
        if(i<cells[0].length-1 /*&& j>0 && j<cells.length-1*/){  // Not bottem and not left and not right
          if(cells[i+1][j].alive = true){
            result++;
          }
        }
        if(j>0 /*&& i>0 && i<cells[0].length-1*/){  // Not left and not top and not bottem
          if(cells[i][j-1].alive = true){
            result++;
          }
        }
        if(j<cells.length-1 /*&& i>0 && i<cells[0].length-1*/){  // Not right and not top and not bottem
          if(cells[i][j+1].alive = true){
            result++;
          }
        }
        if(i > 0 && j > 0){  // If cell isn't on the left border and top border
          if(cells[i-1][j-1].alive = true){
            result++;
          }
        }
        if(i > 0 && j < cells.length-1){  // If cell isn't on the right border and top border
          if(cells[i-1][j+1].alive = true){
            result++;
          }
        }
        if(i < cells[0].length-1 && j > 0){  // If cell isn't on the bottem border and not on left border
          if(cells[i+1][j-1].alive = true){
            result++;
          }
        }
        if(i < cells[0].length-1 && j < cells.length-1){  // If the cell isn't on the right border and the bottem border
          if(cells[i+1][j+1].alive = true){
            result++;
          }
        }
          }}
     
        return result;
      } // end of method
     
      void generationNextCalc(){ // method to count the next generation
     
        for (int i = 0; i < cells[0].length-1; i++){
          for (int j = 0; j < cells.length-1; j++){
            int numNeighbours = numNeighbours(i,j);
            if (numNeighbours < 2 || numNeighbours > 3){
              cells[i][j].setAlive(false);
            }else if (numNeighbours == 3){
                cells[i][j].setAlive(true);
            }
          }
        } 
     
        /* (int j = 1; j < cells.length-1; j++){
          for (int i = 1; i < cells[0].length-1; i++){
            cells[i][j] = cells[i][j];
          }
        }*/
      } // end of method
     
    } // end of class
     
    class Cell{
      boolean alive = false;
      GameOfLife character = new GameOfLife();
     
      boolean isAlive(){
        return alive;   
      } // end of method
     
      void setAlive(boolean state){
        alive = state;
      } // end of method
     
    } // end of class


    --- Update ---

    Quote Originally Posted by angstrem View Post
    Your generationNextCalc method. Try to trace the life of a cell (from the beginning of the method) throughout the loops. Then reason, what changed on your field.
    Also, your cells have only 2 states. You can use booleans to represent them in an array - that's more clean and less memory-consumptive.
    To change it all to boolean takes to long. there is only one erro left. an out of bounderies error, could you see it?

    code:
    import java.util.*;
    import java.io.*;
     
    class GameOfLife{  // main class
      Field field = new Field();
      Scanner scanner;
      File source;
      String filename = "GameOfLifeInput.txt";
      char[] charArray;
     
      public static void main(String[]args){ // starts up program
        new GameOfLife().play();
      } // end of method
     
      void readInitial(String filename){ // reads input from file
        try{
          source = new File(filename);
          scanner = new Scanner(source);
          String line = null;
          int row = 0;
          int col = 0;
          LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
          lnr.skip(Long.MAX_VALUE);
          lnr.getLineNumber();
          Cell[][] cells = new Cell[lnr.getLineNumber()][];
     
          while (scanner.hasNext()){
            line = scanner.nextLine();
            char[] charArray = line.toCharArray();
            cells[row] = new Cell[charArray.length];
            for (Character c : charArray){
              Cell cell = new Cell();
              if (c == ' '){
                cell.setAlive(false);
              }else if (c == '*'){
                cell.setAlive(true);
              }
              cells[row][col] = cell;
              ++col;
            }
          ++row;
          col = 0;
          field.setField(cells);
          }
          //field.setField(cells);
        }catch(FileNotFoundException e){
          System.out.println("Could not find or open file due to \n"+e);
        }catch (IOException e) {}
     
      } // end of method 
     
      void play(){ //Asks user for number of generations and execute those generations with brakes of 2 secs in between them
        try{
          int numberOfGenerations = 0;
          int i = 0;
          scanner = new Scanner(System.in);
          System.out.println("How many generations do you want to see?");
          numberOfGenerations = scanner.nextInt();
          readInitial(filename);
          for(i = 0; i < numberOfGenerations; i++){
            field.print();
            field.generationNextCalc();
            Thread.sleep(2000);
          }
        }catch(InterruptedException e){
        }
      }
    } // end of class
     
    class Field{
      int i, j;
      Cell[][] cells;
     
      void setField(Cell[][] cells){ // method which replaces the empty matrix with the matrix with values read from file
        this.cells = cells;
      }
     
      void drawLine(){ //method to draw lines
        String s = "+";
        for(int i = 1; i < cells[0].length-1; i++){
          s+="--";
        }
        s+="+";
        System.out.println(s);
      } // end of method
     
      public void print(){ //method to print generations
        drawLine();
        for(int i = 1; i < cells.length-1; i++){
          System.out.print("|");
          for(int j = 1; j < cells[i].length-1; j++){
            if(cells[i][j].isAlive()){ 
              System.out.print("*");
            }else{
              System.out.print(" ");
            }
          }
          System.out.println("|");
        }
        drawLine();
     
      } // end of method
     
      int numNeighbours(int i, int j){ // method to count the number of neighbors
        int result = 0;
     
        for(i = 0 ; i<cells[0].length ; i++){
          for(j = 0 ; j<cells.length ; j++){
     
        if(i>0 /*&& j>0 && j<cells.length-1*/){
          if(cells[i-1][j].alive = true){  // Not top and not left and not right
            result++;
          }
        }
        if(i<cells[0].length-1 /*&& j>0 && j<cells.length-1*/){  // Not bottem and not left and not right
          if(cells[i+1][j].alive = true){
            result++;
          }
        }
        if(j>0 /*&& i>0 && i<cells[0].length-1*/){  // Not left and not top and not bottem
          if(cells[i][j-1].alive = true){
            result++;
          }
        }
        if(j<cells.length-1 /*&& i>0 && i<cells[0].length-1*/){  // Not right and not top and not bottem
          if(cells[i][j+1].alive = true){
            result++;
          }
        }
        if(i > 0 && j > 0){  // If cell isn't on the left border and top border
          if(cells[i-1][j-1].alive = true){
            result++;
          }
        }
        if(i > 0 && j < cells.length-1){  // If cell isn't on the right border and top border
          if(cells[i-1][j+1].alive = true){
            result++;
          }
        }
        if(i < cells[0].length-1 && j > 0){  // If cell isn't on the bottem border and not on left border
          if(cells[i+1][j-1].alive = true){
            result++;
          }
        }
        if(i < cells[0].length-1 && j < cells.length-1){  // If the cell isn't on the right border and the bottem border
          if(cells[i+1][j+1].alive = true){
            result++;
          }
        }
          }}
     
        return result;
      } // end of method
     
      void generationNextCalc(){ // method to count the next generation
     
        for (int i = 0; i < cells[0].length-1; i++){
          for (int j = 0; j < cells.length-1; j++){
            int numNeighbours = numNeighbours(i,j);
            if (numNeighbours < 2 || numNeighbours > 3){
              cells[i][j].setAlive(false);
            }else if (numNeighbours == 3){
                cells[i][j].setAlive(true);
            }
          }
        } 
     
        /* (int j = 1; j < cells.length-1; j++){
          for (int i = 1; i < cells[0].length-1; i++){
            cells[i][j] = cells[i][j];
          }
        }*/
      } // end of method
     
    } // end of class
     
    class Cell{
      boolean alive = false;
      GameOfLife character = new GameOfLife();
     
      boolean isAlive(){
        return alive;   
      } // end of method
     
      void setAlive(boolean state){
        alive = state;
      } // end of method
     
    } // end of class

  11. #10
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: When I run my program, it says error: java.lang.NullPointerException

    That's a bad thing that you can't quickly change your implementation: this means, that your code is not flexible.
    "Out of boundary" is too trivial error, try finding it yourself. Just remember, that valid indexes for an array are [0; array.length - 1]

Similar Threads

  1. When I run my program, it says error: java.lang.NullPointerException
    By ProgrammerNoobE in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 28th, 2013, 09:19 AM
  2. Replies: 1
    Last Post: November 27th, 2012, 10:19 AM
  3. [SOLVED] Error Message: Exception in thread "main" java.lang.NullPointerException etc.
    By coffecupcake in forum What's Wrong With My Code?
    Replies: 5
    Last Post: November 15th, 2011, 09:34 AM
  4. [SOLVED] Java run time error: 'java.lang.NullPointerException"
    By ChandanSharma in forum What's Wrong With My Code?
    Replies: 9
    Last Post: June 20th, 2011, 12:53 PM
  5. Getting "AWT-EventQueue-0" java.lang.NullPointerException error
    By tryingtoJava in forum AWT / Java Swing
    Replies: 9
    Last Post: September 21st, 2009, 11:46 PM

Tags for this Thread