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

Thread: Can't run Game of Life programm

  1. #1
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Can't run Game of Life programm

    Hello guys, I'm new here, I was trying my homework for computer science which consists of making a basic Game of Life program with a 2D boolean array and a Random number with a seed, this is what I have so far:
    import java.util.*;
    public class Life 
    {
    	static Scanner console = new Scanner(System.in);
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) 
    	{
     
    		//String file = null;
    		Scanner input;
    		if(args.length > 0)
    		{
    			//file = args[0];
    		}
    		else
    		{
    		    System.out.println("Enter number of rows flowed by number of columns and a seed: ");
    			//file = console.next();
    		}
    		input = new Scanner(console.next());
    		boolean [][] matrix = readInput(input);
    		System.out.println(matrix.length + " " + matrix[0].length);
    		printMatrix(matrix);
     
    	}
     
    	/**
    	 * reads the input already entered by user
    	 * 
    	 */
    	private static boolean[][] readInput(Scanner input)
    	{
    		int numRows;
    		int numCols;
    		Random ran = new Random();
     
    		String message1= "Please enter number of rows, columns, and a seed in that specific order";
    		try
    		{
    			numRows = input.nextInt();
    			numCols = input.nextInt();
    			ran.setSeed(input.nextLong());
    			if (numRows + numCols < 9)
    			{
    				System.out.println("Not enough space for an organism to survive, try again");
    			}
    			boolean[][] matrix = new boolean[numRows][numCols];
    			createMatrix(matrix);
    			for(int row = 1; row < matrix.length - 1; row ++ )
    			{
    				for( int col = 1; col < matrix[row].length - 1; col++)
    				{
     
    					matrix[row][col] = ran.nextBoolean();
     
    				}
    			}
    			return matrix;
    		}
    		catch(NoSuchElementException e)
    		{
    			throw new IllegalStateException(message1);
    		}
     
    	}
     
     
    	/**
    	 * Prints the matrix including the toxic border
    	 * 
    	 */
    	private static void printMatrix(boolean[][] matrix)
    	{
    		for(int r = 0; r < matrix.length; r++)
    		{
    			for(int c = 0; c < matrix[r].length; c++)
    			{
    				System.out.println(matrix[r][c] + " ");
    			}
    			System.out.println();
    		}
    		System.out.println();
     
    	}
     
    	/**
    	 * Initializes a matrix by setting the array's entire content to false
    	 * @param matrix
    	 */
    	private static void createMatrix(boolean[][] matrix)
    	{
    		for(int r = 0; r < matrix.length; r++)
    		{
    			for(int c = 0; c < matrix[r].length; c++)
    			{
    				matrix[r][c] = false;
    			}
     
    		}
     
    	}
     
     
    }
    when I run it and enter the 3 inputs it just gives me the IllegalStateException and I have no idea why, please help


  2. #2
    Junior Member
    Join Date
    Jul 2011
    Posts
    25
    My Mood
    Fine
    Thanks
    1
    Thanked 4 Times in 4 Posts

    Default Re: Can't run Game of Life programm

    you have used two Scanner objects and second object has only one character read from first object it doesn't have 3 characters
    to resolve your problem use just first object when calling readInput(console) method.

  3. The Following User Says Thank You to serdar For This Useful Post:

    cutekill0 (September 3rd, 2011)

  4. #3
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Cool Re: Can't run Game of Life programm

    Wow thank you very much, also on my printMatrix method the output should be a '-' for false and a '#' for true, any ideas how I can do this?
    Again thank you a lot

  5. #4
    Junior Member
    Join Date
    Jul 2011
    Posts
    25
    My Mood
    Fine
    Thanks
    1
    Thanked 4 Times in 4 Posts
    Last edited by serdar; September 3rd, 2011 at 01:14 AM.

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    output should be a '-' for false and a '#' for true
    The tri compare statement could work:
    String val = (boolean ? "#" : "-");

  7. #6
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    ok so I changed the printMatrix method to look like this
    private static void printMatrix(boolean[][] matrix)
    	{
    		for(int r = 0; r < matrix.length; r++)
    		{
    			for(int c = 0; c < matrix[r].length; c++)
    			{
    				if(matrix[r][c] = false)
    				{
    					System.out.println( "#");
    				}
    				else
    				{
    					System.out.println("-");
    				}
    			}
    			System.out.println();
    		}
    		System.out.println();
     
    	}
    I should be getting an output that looks like this:
    – – – – – – – –
    – # # # – – – –
    – # # # # – # –
    – – – # # – # –
    – # – # – ## –
    – – – – – – – –

    instead of that I'm getting straight-down '–' , any ideas why?

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    if(matrix[r][c] = false)
    That is an assignment statement not a comparison.

    You do NOT need to compare the value of a boolean. Use its value directly:
    if(!matrix[r][c])

  9. The Following User Says Thank You to Norm For This Useful Post:

    cutekill0 (September 3rd, 2011)

  10. #8
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    Hello again guys, I was cleaning up my code and doing tests and I wanted to ask if you recommend any way to stop the program if only 2 inputs are typed, like throwing an exception if the user only enters the number of rows and columns,
    Thanks in advance

  11. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    You can use the Scanner's has... method to detect if there is any input to read.
    Will that allow you to detect that the user has not entered all the input you want?
    Try it and see what the effect is.

  12. #10
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    I tried it and the program just waits for a third input, after a third input its when the program stops, I guess making it so it stops at 2 inputs would not matter

  13. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    Can you explain what your problem is now?

  14. #12
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    Its not really a problem, I was just trying to create an if loop trying to stop the program after just 2 inputs, but when I run the program and I write just 2 numbers, it just continues running waiting for me to enter a third digit, this is what I wrote:
    if(console.hasNextInt())
    {
    numRows = console.nextInt();
    numCols = console.nextInt();
    casual.setSeed(console.nextLong());
    }
    else
    {
     throw new IllegalStateException(message1);
    }
    I entered 7 8 as input, pressed Enter and the programs just stays waiting for a third digit, I'm tying to make it so it produces a message saying that the user needs to enter one last number

  15. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    I don't know if there is an easy way to exit from a next method that is waiting for user input.
    What if you ask separately for each of the inputs so the user knows what the next number to be entered should be?

  16. #14
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    Great idea, I'll try it out, thanks much

  17. #15
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    so now my program needs to read the parameters from standard input. The new inputs for this part are the values for the ranges, birthLow, birthHigh, liveLow, and liveHigh. I need to read the matrix like before and then repeat for five iteration of updating the matrix and printing the result.

    I need to calculate the number of entities in the neighborhood and compare the count with the birth range (if the cell is empty) or live range (if there was already an entity there) the count must be based on the values as of the previous iteration. I will need to make a copy of the matrix before doing the updates so that I can count entities in neighborhoods based on original values.
    I am completely lost and I wrote some stuff that a friend explained but I don't even know if its right, please please help!!!!
    here's what I have:
    * Simple I/O of the Game of Life
     * @author Eddy Guzman (edguzman@marauder.millersville.edu)
     *
     */
    import java.util.*;
    public class Life 
    {
     
     
    	/**
    	 * Our main method, the user enters the number of rows followed by the number of columns and the seed
    	 * @param args
    	 */
    	public static void main(String[] args) 
    	{
    	    Scanner console = new Scanner(System.in);
    		System.out.println("Enter number of rows followed by number of columns and a seed: ");
    		boolean [][] matrix = readInput(console);
    		printMatrix(matrix);
    		nextMatrix(matrix);
     
    	}
     
    	/**
    	 * 
    	 * Reads the input already entered by user. If the space available in the grid is not enough
    	 * for an organism to survive, the program will throw an IllegalStateException
    	 * Returns the matrix array after all the 3 inputs have been entered.
    	 * 
    	 */
    	private static boolean[][] readInput(Scanner console)
    	{
    		int numRows;
    		int numCols;
    		Random casual = new Random();
    		String message1= "Please enter number of rows, columns, and a seed in that specific order";
    		try
    		{
     
    			numRows = console.nextInt();
    			numCols = console.nextInt();
    			if (numRows + numCols < 9)//this is to check that there is space for an organism to survive
    			{
     
    				throw new IllegalStateException("Not enough space for an organism to survive, try again");
     
    			}
    			casual.setSeed(console.nextLong());
    			System.out.println();
    			boolean[][] matrix = new boolean[numRows][numCols];
     
    			createMatrix(matrix);
    			for(int row = 1; row < matrix.length - 1; row ++ )
    			{
    				for( int col = 1; col < matrix[row].length - 1; col++)
    				{
     
    					matrix[row][col] = casual.nextBoolean();
     
    				}
    			}
     
    			return matrix;
    		}
    		catch(NoSuchElementException e)
    		{
    			throw new IllegalStateException(message1);
    		}
    		catch (StringIndexOutOfBoundsException e) 
    		{
    			throw new IllegalStateException(message1);
    		}
     
    	}
     
     
    	/**
    	 * Prints the matrix including the deadly border
    	 * @param matrix - uses the values in the matrix to print it
    	 */
    	private static void printMatrix(boolean[][] matrix)
    	{
    		System.out.println("Here's the matrix");
    		for(int r = 0; r < matrix.length; r++)
    		{
    			for(int c = 0; c < matrix[r].length; c++)
    			{
    				if(!matrix[r][c])
    				{
    					System.out.print( " – " );
    				}
    				else
    				{
    					System.out.print(" # ");
    				}
    			}
    			System.out.println();
    		}
    		System.out.println();
     
    	}
     
    	/**
    	 * Initializes a matrix by setting the array's entire content to false
    	 * @param matrix - uses the length of the matrix to set it all to false
    	 */
    	private static void createMatrix(boolean[][] matrix)
    	{
    		for(int r = 0; r < matrix.length; r++)
    		{
    			for(int c = 0; c < matrix[r].length; c++)
    			{
    				matrix[r][c] = false;
    			}
     
    		}
     
    	}
     
    	/**
    	 * 
    	 * @param matrix
    	 */
    	private static void nextMatrix(boolean[][] matrix)
    	{
    		boolean [][] newMatrix = matrix.clone();
    		for (int row = 1; row < matrix.length; row++)
    		 {
    		       for (int col = 1; col < matrix.length; col++)
    		       {
     
    		        newMatrix[row][col] = matrix[row][col];
     
    		        int count = countNeighbors ( newMatrix , row, col );
     
    		        switch (count)
    		        {
    		            case 0: case 1:
    		                    newMatrix[row][col]=false;
    		                break;
     
    		            case 2: 
    		                if(newMatrix[row][col])
    		                {
    		                	newMatrix[row][col] = true;
    		                }
     
     
    		                if(!newMatrix[row][col])
    		                {
    		                	newMatrix[row][col]=false;
    		                }
     
    		                break;
     
    		            case 3:
    		                    newMatrix[row][col]=true;
    		                break;
     
    		            case 4: case 5: case 6: case 7: case 8:
    		                newMatrix[row][col]=false;
    		                break;
    		         }
     
    		        matrix [row][col] = newMatrix[row][col];
    		        }
    		    }
     
    	}
     
    	/**
    	 * 
    	 * @param newMatrix
    	 * @param row
    	 * @param col
    	 * @return
    	 */
     
    	private static int countNeighbors(boolean[][] matrix, int row, int col)
    	{
     
    		int ncount = 0;
            for(int r = row - 1; r <= row+1; r++) 
            {
                if(row < 0 || row >= matrix.length ) 
                {
                    continue;
                }
                for(int c = col - 1; c <= col + 1; c++) 
                {
                    if(col < 0 || col >= matrix.length || (r == row && c == col)) 
                    {
                        continue;
                    }
                    if(matrix[row][col]) 
                    {
                        ncount++;
                    }
                }
            }
            return ncount;
        }
     
     
     
    }

  18. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    Take it one step at a time.
    Do you have it going through the 5 cycles yet?
    Get that working before trying to save and display the statistics.

  19. #17
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    that's one of my question, do I have to do the console.nextInt() in the same readInput method, or do I need to create a new one?

  20. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    A suggestion for testing.
    Forget about getting input from the user until you get the program's logic working. Hard code some good testing values for now:
    numRows = 8; //console.nextInt();
    numCols = 8; //console.nextInt();

  21. #19
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    ok but where should I initialize the other 5 variables?

  22. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    What other 5 variables?

  23. #21
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    the ranges: birthLow, birthHigh, liveLow, and liveHigh 4 in total my mistake
    For a birth to occur, the cell must be empty and the neighborhood density be in the birth range. The birth range can be given as two integers from zero to nine, birthLow and birthHigh, so that a birth will occur if the cell is empty and the neighborhood population is at least birthLow and no more than birthHigh. Similarly, a death occurs in a cell if there is an organism there and the neighborhood has less than the minimum population for survival, or greater than the maximum. Hence there is a live range provided as two integers from zero to nine, liveLow and liveHigh.

  24. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    Are any of those variables in the code you posted?
    I only see three places where you read in data from the user.

  25. #23
    Junior Member cutekill0's Avatar
    Join Date
    Sep 2011
    Posts
    20
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't run Game of Life programm

    that's one place I'm having trouble with, I'm not sure where I need to use them

  26. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,094
    Thanks
    48
    Thanked 2,152 Times in 2,125 Posts

    Default Re: Can't run Game of Life programm

    You need to read the assignment again.
    Also go to wikipedia and read about the Game of Life so you understand what the program is supposed to do.

  27. #25
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,256
    My Mood
    Hungover
    Thanks
    142
    Thanked 618 Times in 529 Posts

    Default Re: Can't run Game of Life programm

    Recommended reading: How to Program (stuck on homework? READ THIS BEFORE POSTING)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  28. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Norm (September 13th, 2011)

Similar Threads

  1. Conways Game of Life. Long Death option. Please help..
    By byako in forum What's Wrong With My Code?
    Replies: 8
    Last Post: March 9th, 2011, 07:49 AM
  2. Read in file and store in 2D array start of The Game of Life
    By shipwills in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 2nd, 2011, 08:52 AM
  3. Game of Life GUI Error
    By Lavace in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 3rd, 2011, 08:15 AM
  4. im in a hurry!!Help with a programm..java game of guessing a word
    By mr_doctor in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 13th, 2010, 08:17 AM
  5. Replies: 1
    Last Post: March 28th, 2009, 07:21 AM