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 4 of 4

Thread: Problem with lists

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problem with lists

    I have an assignment for college that involves placing randomly chosen words from a text file into a 2-d array. I have nearly completed ithowever I am having difficulty with a list of string type.

    What I have done so far is below, sorry its long...
    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
    import java.io.*;
    import java.lang.Math;
     
    public class WordSearchPuzzle
    {
        private char[][] puzzle;
        private List<String> puzzleWords;
        private List<String> wordsForGrid;
        private int gridDimension;
        private char [] alphabet;
     
        public WordSearchPuzzle(List<String>userSpecifiedWords)
        {
            gridDimension = sizeOfGrid(puzzleWords);
            this.puzzle = new char[gridDimension][gridDimension];//grid is going to be a square
            this.puzzleWords=userSpecifiedWords;
     
        }
        public WordSearchPuzzle(String wordFile, int wordCount, int shortest, int longest)
        {
            int temp;
            if(shortest>longest)
            {
                temp=longest;
                longest=shortest;
                shortest=temp;
            }
            puzzleWords = loadWordsFromFile(wordFile,shortest,longest);
            for(int i=0;i<wordCount;i++)
            {
                int pos=(int)(Math.random()*puzzleWords.size());    
                wordsForGrid.add(puzzleWords.get(pos));            
            }
            int gridDimension = sizeOfGrid(puzzleWords);
            this.puzzle = new char[gridDimension][gridDimension];
            puzzleWords=wordsForGrid;
     
     
        }
        public int sizeOfGrid(List<String> puzzleWords)
        {
            double temp=0;
            int gridDimension;
            for(int i=0;i<puzzleWords.size();i++)
            {
                temp+=puzzleWords.get(i).length();
            }
            temp =Math.sqrt(temp);
            temp=(int)(temp*1.75);//scalling up by a factor of 1.75 as suggested;
            gridDimension=(int)(temp);
            return gridDimension;
        }
        /*public void fillGrid (List<String> puzzleWords)
        {
            for(int i=0;i<puzzleWords.size();i++)
            {
            }
     
        }*/
        private List<String> loadWordsFromFile(String wordFile, int shortest, int longest)
        {
            try
            {
                FileReader aFileReader = new FileReader(wordFile);
                BufferedReader aBufferReader = new BufferedReader(aFileReader);
                String lineFromFile;
                List <String>words=new ArrayList<String>();//would not let me create an empty List, created an ArrayList insead.
                lineFromFile = aBufferReader.readLine();
                int wordLength;
                while(lineFromFile!=null)
                {
                    wordLength=lineFromFile.length();
                    if(wordLength>=shortest&&wordLength<=longest)
                    {
                        words.add(lineFromFile);
                    }
                    lineFromFile=aBufferReader.readLine();
                }
                aBufferReader.close();
                aFileReader.close();
                return words;
            }
            catch (IOException x)
            {
                return null;
            }
        }
        public List<String> getWordSearchList()
        {
            return this.puzzleWords;       
        }
     
        public char[][]getPuzzleAsGrid()
        {
            int i;
            int j;
            alphabet =new char []{('a'),('b'),('c'),('d'),('e'),('f'),('g'),('h'),('i'),('j'),('k'),('l'),('m'),('n'),('o'),('p'),('q'),('r'),('s'),('t'),('u'),('v'),('w'),('x'),('y'),('z')};
     
            for(i=0;i<puzzle.length;i++)
            {
                for(j=0;j<gridDimension;j++)
                {
                    int randomChar = (int)(Math.random()*alphabet.length);
                    this.puzzle[i][j]=alphabet[randomChar];
                    System.out.print(puzzle[i][j]+"");
                }
                System.out.println();
            }
            return puzzle;
        }
        public String getPuzzleAsString()
        {   
            int i;
            int j;
            String puzzleString="";
            for(i=0;i<gridDimension;i++)
            {
                for(j=0;j<gridDimension;j++)
                {
                    puzzleString+=puzzle[i][j];
                }
                if(i==gridDimension)
                {
                    puzzleString+="\n";
                }
            }
            return puzzleString;
        }
        public void showWordSearchPuzzle()
        {
            generateWordSearchPuzzle();
            for(int i=0;i<puzzleWords.size();i++)
            {
                System.out.println(puzzleWords.get(i));
            }
        }
        public void generateWordSearchPuzzle()
        {
           int j=0;//to be used to check if the space where the current word is supposed to go is empty
           int i;//to be used to go through the list of words
           int k;//to be used to get the individual character from the current word
           int randomDirection;//determine which direction to place the word
           int randomRow;//starting position for word
           int randomCol;//starting position for word
           for(i=0;i<puzzleWords.size();)
           {
              randomDirection = (int)(Math.random()*4);
              randomRow=(int)(Math.random()*gridDimension);
              randomCol=(int)(Math.random()*gridDimension);
              int randomColTemp = randomCol;
              int randomRowTemp = randomRow;
              if(randomDirection==0)//word being placed to the right
              {
                  if(gridDimension-(randomCol+1)>=puzzleWords.get(i).length())
                  {
                      for(j=0;j<puzzleWords.get(i).length();j++)
                      {
                        if(puzzle[randomRow][randomColTemp]==0)
                        {
                            randomColTemp++;
                        }
                        else
                        j=puzzleWords.get(i).length()+1;//space is not empty,want to break the loop
                      }
                  }
                  if(j==puzzleWords.get(i).length())
                  {
                      for(k=0;k<puzzleWords.get(i).length();)
                      {
                          puzzle[randomRow][randomCol]=puzzleWords.get(i).charAt(k);
                          randomCol++;
                          k++;
                      }
                      i++;
                  }
              }
              if(randomDirection==1)//word being placed to the left)
              {
                  if(randomCol+1>=puzzleWords.get(i).length())
                  {
                      for(j=0;j<puzzleWords.get(i).length();j++)
                      {
                          if(puzzle[randomRow][randomColTemp]==0)
                          {
                              randomColTemp--;
                          }
                          else
                          j=puzzleWords.get(i).length()+1;
                      }
                  }
                  if(j==puzzleWords.get(i).length())
                  {
                      for(k=0;k<puzzleWords.get(i).length();)
                      {
                          puzzle[randomRow][randomCol]=puzzleWords.get(i).charAt(k);
                          randomCol--;
                          k++;
                      }
                      i++;
                  }
              }
              if(randomDirection==2)//word being placed vertically down
              {
                  if(gridDimension-(randomRow+1)>=puzzleWords.get(i).length())
                  {
                      for(j=0;j<puzzleWords.get(i).length();j++)
                      {
                          if(puzzle[randomRowTemp][randomCol]==0)
                          {
                              randomRowTemp++;
                          }
                          else
                          j=puzzleWords.get(i).length()+1;
                      }
                  }
                  if(j==puzzleWords.get(i).length())
                  {
                      for(k=0;k<puzzleWords.get(i).length();)
                      {
                          puzzle[randomRow][randomCol]=puzzleWords.get(i).charAt(k);
                          randomRow++;
                          k++;
                      }
                      i++;
                  }
              }
              if(randomDirection==3)//word being placed vertically up
              {
                  if(randomRow+1>=puzzleWords.get(i).length())
                  {
                      for(j=0;j<puzzleWords.get(i).length();j++)
                      {
                          if(puzzle[randomRowTemp][randomCol]==0)
                          {
                              randomRowTemp--;
                          }
                          else
                          j=puzzleWords.get(i).length()+1;
                        }
                  }
                  if(j==puzzleWords.get(i).length())
                  {
                      for(k=0;k<puzzleWords.get(i).length();)
                      {
                          puzzle[randomRow][randomCol]=puzzleWords.get(i).charAt(k);
                          randomRow--;
                          k++;
                      }
                      i++;
                  }
              }
           }
           for(int l=0;i<gridDimension;i++)
           {
               for(int m=0;j<gridDimension;j++)
               {
                   if(puzzle[l][m]==0)
                   {
                       int randomAlphabeticChar = (int)(Math.random()*alphabet.length);
                       puzzle[l][m]=alphabet[randomAlphabeticChar];
                   }
               }
           }
        }
    }

    when I try to run an instance of the program(using BlueJ) I get an error saying there is a null pointer exception at line 35 which is
    wordsForGrid.add(puzzleWords.get(pos));
    I am thinking that this is related to the fact that at this line in the loadWordsFromFile method
    List <String>words=new ArrayList<String>();
    I could not create an empty list of string type, i.e List<String>words = new List<String>();

    Is this correct? Or am I looking in the wrong place. The textfile I am using contains over 6000 words on a separate line for each if that makes any difference. I would appreciate any help or guidance with this.
    Thanks


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Problem with lists

    This statement declares the variable wordsForGrid:

    private List<String> wordsForGrid; // line 11

    but it doesn't initialize it, as in:

    wordsForGrid = new ArrayList<String>(); // due to type inference, 'String' is optional in Java 7 and above

    The uninitialized variable is therefore 'null'. The initialization would normally occur in the constructor.

  3. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problem with lists

    Thanks for the quick reply, seems to have solved the problem for me.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Problem with lists

    You're welcome. Glad to help.

Similar Threads

  1. Help with initializing Lists
    By Jumbosize in forum Collections and Generics
    Replies: 1
    Last Post: May 28th, 2012, 02:47 PM
  2. Serialization of lists
    By colerelm in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 5th, 2011, 10:39 PM
  3. Operations with lists
    By datreta in forum Collections and Generics
    Replies: 8
    Last Post: October 29th, 2010, 08:54 AM
  4. Linked Lists
    By Jnoobs in forum Java Theory & Questions
    Replies: 1
    Last Post: October 23rd, 2010, 04:09 PM
  5. Lists of Sets and Sets of Lists
    By Newoor in forum Collections and Generics
    Replies: 2
    Last Post: December 8th, 2009, 08:13 PM