java.lang.NullPointerException tictactoe程序

时间:2016-11-21 04:45:43

标签: java arrays nullpointerexception

我一直在:

Exception in thread "main" java.lang.NullPointerException
at TTTPlayer.setBoard(TTTPlayer.java:55)    
at TTTPlayer.inputMethod(TTTPlayer.java:35)     
at TTTPlayer.main(TTTPlayer.java:23)

我的程序是一个tictactoe程序,我试图将人输入的值设置为相应的数组索引,然后可以打印出来。我知道我还没有一个翻转器用于转换玩家。我虽然无法解决这个问题。

import java.util.*;

public class TTTPlayer {

    public static String[][] board;
    public static String currentPlayer;

    public TTTPlayer() {
        currentPlayer = "x";
        board = new String[3][3];
        board[0][0] = "1";
        board[0][1] = "2";
        board[0][2] = "3";
        board[1][0] = "4";
        board[1][1] = "5";
        board[1][2] = "6";
        board[2][0] = "7";
        board[2][1] = "8";
        board[2][2] = "9";
    }

    public static void main(String[] args) {
        inputMethod();
    }

    public static void inputMethod()
    {
        TicTacToeMain.printBoard();
        Scanner Input = new Scanner(System.in);
        System.out.println("Enter what square you would like to place in.");
        String choice = Input.nextLine();

        if(choice.equals("1")||choice.equals("2")||choice.equals("3")||choice.equals("4")||choice.equals("5")||choice.equals("6")||choice.equals("7")||choice.equals("8")||choice.equals("9"))
        {   
            setBoard(choice);

        }   
        else
        {   
            System.out.println("That is not a valid choice, please retry.");
            inputMethod();

        }   

    }
    public static void setBoard(String choice)
    {
        String choice1 = choice;

         for (int i = 0; i < 3; i++) {


            for (int j = 0; j < 3; j++) {

               if(board[i][j].equals(choice1)){
                  board[i][j].equals(currentPlayer);
                  printBoard();

               }

            }
        }
        //System.out.println(choice1);  
    }

    public static void printBoard()
    {  
       System.out.println(board[0][0]+" | "+board[1][0]+" | "+board[2][0]);
       System.out.println("——|———|——");
       System.out.println(board[0][1]+" | "+board[1][1]+" | "+board[2][1]);
       System.out.println("——|———|——");
       System.out.println(board[0][2]+" | "+board[1][2]+" | "+board[2][2]);

    }
}

1 个答案:

答案 0 :(得分:2)

main中,您需要实例化TTTPlayer对象。还要使类方法非静态。

public static void main(String[] args) {
    TTTPlayer player = new TTTPlayer ();
    player.inputMethod();
}

public static void inputMethod() -> public void inputMethod()