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

Thread: Methods, Booleans, and Initializing, OH MY!!

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Methods, Booleans, and Initializing, OH MY!!

    Ok, so I want to start off by saying that I am finishing my Associates in Computer Information Systems, and I AM NOT A PROGRAMMER!! I am not good at it and it is extremely difficult for me to wrap my head around it (which is odd for me because I love to learning; I am learning to speak Russian just for fun).

    So, my assignment is to fill in the blanks of code with my own to get the outcome of a tic tac toe game. Here is all of the code:

    /*
     * 
     */
    package tictactoe;
     
    /**
     *
     * @author Gorgo
     */
    public class TicTacToe {
    // #2. variable and constant declarations - given by book
    	static int [][] gameboard;
    	static final int EMPTY = 0;
    	static final int NOUGHT = -1;   //PLAYER O
    	static final int CROSS = 1;	//PLAYER X
     
     
    	// #3. utility methods - given by book
    	static void set(int val, int row, int col) 
                    throws IllegalArgumentException {
    			if (gameboard[row][col] == EMPTY)
    				gameboard[row][col] = val;
    			else throw new IllegalArgumentException
    				("Player already there!");
    		}
     
     
    	static void displayboard() {
    		for (int r = 0; r < gameboard.length; r++) {
    			System.out.print ("|");
    				for (int c = 0; c < gameboard[r].length; c++) {
    					switch (gameboard[r][c]) {
    						case NOUGHT:
    							System.out.print("O");
    							break;
    						case CROSS:
    							System.out.print("X");
    							break;
    						default:		//Empty
    							System.out.print(" ");
    					}
    					System.out.print("|");
    				}
    				System.out.println("\n--------\n");
    		}
    	}
     
    	// #5. define createBoard method - MY CODE
    	static void createBoard(int rows, int cols) {
                //#6. Initialize gameboard
                int[][] createBoard = new int[rows][cols];
                    for (int r = 0; r < 3; r++) {
                        for (int c = 0; c < 3; c++) {
                            createBoard[rows][cols] = -1;
                        }
                    }
     
            }
     
            //#6. define winOrTie method - MY CODE
            static boolean winOrTie() {
                // #6. determine whether X or O won or there is a tie - MY CODE               
                int winner = -2;
     
                for (int r = 0; r < 3; r++)
                    if ((gameboard[r][0] == winner) && (gameboard[r][1] == winner)
                            && (gameboard[r][2] == winner)) {
                        return true;
                    }
    		for (int j = 0; j < 3; j++)
    			if ((gameboard[0][j] == winner) && (gameboard[1][j] == winner)
    					&& (gameboard[2][j] == winner)) {
    				return true;
    			}
     
    		if ((gameboard[0][0] == winner) && (gameboard[1][1] == winner)
    				&& (gameboard[2][2] == winner)) {
    			return true;
    		}
     
    		if ((gameboard[0][2] == winner) && (gameboard[1][1] == winner)
    				&& (gameboard[2][0] == winner)) {
    			return true;
    		}
     
    		return false;                    
     
            } 
     
        public static void main(String[] args) {
            //#8. contents of main() - given by book
          displayboard();
          int turn = 0;
          int playerVal;
          int outcome;
     
          java.util.Scanner scan = new java.util.Scanner(System.in);
     
          do {
     
                playerVal = (turn % 2 == 0) ? NOUGHT: CROSS;
     
                if (playerVal == NOUGHT)
                    System.out.println ("\n-O's turn-");
                        else System.out.println ("\n-X's turn-");
                            System.out.print ("Enter row and column:");
     
                try {
                    set (playerVal, scan.nextInt(), scan.nextInt());
                }
                catch (Exception ex)
                    {System.err.println(ex);}
     
                turn++;
                    outcome = winOrTie();
    		}
     
            while ( outcome == -2 );
                displayboard();
                        switch (outcome) {
                            case NOUGHT:
                                System.out.println("O wins!");
                                    break;
                            case CROSS:
                                System.out.println("X wins!");
                                    break;
                            case 0:
                                System.out.println("Tie.");
                                    break;
                        }
    }	        
    }

    So, the errors that I am getting are:
    #1. "Exception in thread "main" java.lang.NullPointerException"
    this is pointing to the 'displayboard' method:
    static void displayboard() {
    		for (int r = 0; r < gameboard.length; r++) {   //here at this line
    			System.out.print ("|");
    and here:
     public static void main(String[] args) {
            //#8. contents of main()
          displayboard();  //here at this line
          int turn = 0;
          int playerVal;
          int outcome;

    My problem that I am having with these errors is: 1. these particular lines of code were given to me; I did not write them; 2. I don't understand why it is pointing at the first bit. Everything that I have read in my text book says the exact same code.

    Therefore, my question is why is this one line (the 'displayboard method') an error.

    Thank you all in advance


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Methods, Booleans, and Initializing, OH MY!!

    NPEs occur when you attempt to dereference (use the dot operator) on a null value. The line you're getting your NPE only contains one derference on your gameboard variable, so my guess is that gameboard is null. You can step through this with a debugger or add some print statements to check that assumption.

    When do you initialize gameboard?
    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!

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

    NickieBoren (August 30th, 2013)

  4. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Methods, Booleans, and Initializing, OH MY!!

    Well, I really don't know. There are so many 'boards' being initiated. As I am looking over my code, I don't see the "gameboard" being initiated. And to be honest, I don't know where I would initiate it. Would it be under the CreateBoard method?

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

    Default Re: Methods, Booleans, and Initializing, OH MY!!

    Please quit playing the dumb blonde and make an effort. If you don't, you won't get much help, unless Norm happens by.

    You could search for "gameboard" in whatever editor you're using and find every mention of gameboard and probably see where it is being initiated. If you can neither search for nor recognize the initialization when you see it (even thought the initialization is commented in the code), then you should read the book from which this problem came. You may have to start at the beginning.

    This is a pretty complicated assignment for someone who claims to know as little as you do, and we don't have the time or the desire to teach you what you apparently have missed, for free anyway. Someone might take you on as a paid project. We'll help you for free, but you need to make an effort. And we can't write the program for you.

  6. #5
    Junior Member
    Join Date
    Aug 2013
    Posts
    8
    My Mood
    Nerdy
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Methods, Booleans, and Initializing, OH MY!!

    UPDATE: Yeah!! I got it almost running!! I apologize, I am super excited... because, like I said, I am NOT a programmer. Ok, so I have one last error. And I can proudly say that it is not my code. (Confession, the errors before were my fault; I have learned from them and now I am moving on )

    So, here is my updated code:

    /*
     * 
     */
    package tictactoe;
     
    /**
     *
     * @author Gorgo
     */
    public class TicTacToe {
    // #2. variable and constant declaraions
    	static int [][] gameboard;
    	static final int EMPTY = 0;
    	static final int NOUGHT = -1;   //PLAYER O
    	static final int CROSS = 1;	//PLAYER X
     
     
    	// #3. utility methods
    	static void set(int val, int row, int col) 
                    throws IllegalArgumentException {
    			if (gameboard[row][col] == EMPTY)
    				gameboard[row][col] = val;
    			else throw new IllegalArgumentException
    				("Player already there!");
    		}
     
     
    	static void displayboard() {      
    		for (int r = 0; r < gameboard.length; r++) {
    			System.out.print ("|");
    				for (int c = 0; c < gameboard[r].length; c++) {
    					switch (gameboard[r][c]) {
    						case NOUGHT:
    							System.out.print("O");
    							break;
    						case CROSS:
    							System.out.print("X");
    							break;
    						default:		//Empty
    							System.out.print(" ");
    					}
    					System.out.print("|");
    				}
    				System.out.println("\n--------\n");
    		}
    	}
     
    	// #5. define createBoard method
    	static void createBoard(int rows, int cols) {         
                //#6. Initialize gameboard
                int[][] createBoard = new int[rows][cols];
                    for (int r = 0; r < 3; r++) {
                        for (int c = 0; c < 3; c++) {
                            createBoard[r] = createBoard[c];
                        }
                    }
     
            }
     
            //#6. define winOrTie method
            static boolean winOrTie() {
                // #6. determine whether X or O won or there is a tie                
                int winner = -2;
     
                for (int r = 0; r < 3; r++)
                    if ((gameboard[r][0] == winner) && (gameboard[r][1] == winner)
                            && (gameboard[r][2] == winner)) {
                        return true;
                    }
    		for (int j = 0; j < 3; j++)
    			if ((gameboard[0][j] == winner) && (gameboard[1][j] == winner)
    					&& (gameboard[2][j] == winner)) {
    				return true;
    			}
     
    		if ((gameboard[0][0] == winner) && (gameboard[1][1] == winner)
    				&& (gameboard[2][2] == winner)) {
    			return true;
    		}
     
    		if ((gameboard[0][2] == winner) && (gameboard[1][1] == winner)
    				&& (gameboard[2][0] == winner)) {
    			return true;
    		}
     
    		return false;                    
     
            } 
     
        public static void main(String[] args) {
            //#8. contents of main()
          createBoard(3,3);
          int turn = 0;
          int playerVal;
          int outcome;
     
          java.util.Scanner scan = new java.util.Scanner(System.in);
     
          do {
     
                playerVal = (turn % 2 == 0) ? NOUGHT: CROSS;
     
                if (playerVal == NOUGHT)
                    System.out.println ("\n-O's turn-");
                        else System.out.println ("\n-X's turn-");
                            System.out.print ("Enter row and column:");
     
                try {
                    set (playerVal, scan.nextInt(), scan.nextInt());
                }
                catch (Exception ex)
                    {System.err.println(ex);}
     
                turn++;
                    outcome = winOrTie();  // ERROR IS HERE: "required: int  found: boolean"
    		}
     
            while ( outcome == -2 );
                displayboard();
                        switch (outcome) {
                            case NOUGHT:
                                System.out.println("O wins!");
                                    break;
                            case CROSS:
                                System.out.println("X wins!");
                                    break;
                            case 0:
                                System.out.println("Tie.");
                                    break;
                        }
    }	        
    }

    I understand what this error message is saying, however I don't know how to correct the BOOK'S code. The method 'winOrTie()' needs to run at some time, I just don't know when. And I don't know what int to put there to make this statement correct.

    --- Update ---

    Quote Originally Posted by GregBrannon View Post
    Please quit playing the dumb blonde and make an effort. If you don't, you won't get much help, unless Norm happens by.

    You could search for "gameboard" in whatever editor you're using and find every mention of gameboard and probably see where it is being initiated. If you can neither search for nor recognize the initialization when you see it (even thought the initialization is commented in the code), then you should read the book from which this problem came. You may have to start at the beginning.

    This is a pretty complicated assignment for someone who claims to know as little as you do, and we don't have the time or the desire to teach you what you apparently have missed, for free anyway. Someone might take you on as a paid project. We'll help you for free, but you need to make an effort. And we can't write the program for you.
    That is very rude of you. I AM trying. I have been searching the internet and trying desperately to understand and do this on my own. Coming here was a last resort. But I had no idea that people like you were on here and making people like me feel even worse.
    You know, if you don't have anything nice to say, then maybe you shouldn't say anything at all.
    And you're right, I don't know very much about programming, programming languages, let-alone Java. I thought that I could come here and get pointed in the right direction and not be criticized or judged.
    I am not working my butt off on this degree to program. These classes are required. I am working towards specializing in Systems Analysis and Design. And my bachelors is in Business, not programming.
    So, before you go spouting off your judgments, maybe you should rethink your choice of words.

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

    Default Re: Methods, Booleans, and Initializing, OH MY!!

    That's better. Welcome back!

    Inspect the winOrTie() method to determine what it does, what it returns, and how that return can be useful.

    There's an assumption made by that method (I think) that may not be obvious, but it's kind of like the riddle, "Where do you always find the thing you're looking for?" You can use the assumption made by the winOrTie() method to determine whether 'X' or 'O' won the game and then set the variable outcome.

  8. #7
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Methods, Booleans, and Initializing, OH MY!!

    Quote Originally Posted by NickieBoren View Post
    The method 'winOrTie()' needs to run at some time, I just don't know when.
    Every time it has become possible for a win or a tie... immediately after every move is made.

    Quote Originally Posted by NickieBoren View Post
    I am not working my butt off on this degree to program. These classes are required. I am working towards specializing in Systems Analysis and Design. And my bachelors is in Business, not programming.
    Food for thought: Those classes are required for a reason.

Similar Threads

  1. [SOLVED] Advice on booleans and yes/no inputs that deliver specific outputs
    By LeaAnn0223 in forum Loops & Control Statements
    Replies: 9
    Last Post: January 2nd, 2013, 09:44 PM
  2. Initializing
    By whome in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 26th, 2012, 07:07 PM
  3. Initializing and Receiving Variables, Creating Methods
    By RadiantChaos in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 11th, 2012, 12:01 PM
  4. [SOLVED] Not initializing
    By Topflyt in forum What's Wrong With My Code?
    Replies: 9
    Last Post: November 30th, 2011, 04:32 AM
  5. Program is attempting to change booleans yet the result is unsuccesful.
    By CoolGuy134 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: September 26th, 2011, 08:48 AM