簡體   English   中英

Java板陣列故障

[英]Java board array trouble

我正在開發一個使用ansi代碼創建戰艦游戲的程序。 ansi代碼沒什么大問題,因為我發現這些代碼使我可以覆蓋打印行。 我的計划是使用它來將船放置在已經繪制好的板上。 我的問題在於放置飛船的數組(“ 0”)。 似乎無法克服nullpointerexception錯誤。 我覺得這是唯一阻止我完成程序的事情。 任何幫助將不勝感激。

我的程序的一部分在下面。

座標類別:

public class Coordinate {
   public String piece;
   int row, col, type;
   public boolean select, empty, hit, ship;
   public String [][] shipPiece;

   public String section()
   {
       piece = "i";

       empty = true;
       select = false;
       hit = false;
       //ship = false;

       if (empty)
       {
           piece = "\033[33m0\033[0m";
       }
       else if(!empty)
       {
           //empty = true;
           ship = true;
           piece = "0";
       }
       else if(!hit && ship)
           piece = "\033[33m0\033[0m";

       return piece;
   }

   public String placeShip()
   {
       for(int x = 0; x<=10; x++)
       {
           for(int y = 0; y<=10; y++)
           {
               shipPiece[x][y] = piece;
           }
       }
       return piece;   
   }
}

玩家等級:

public class Player {

    private String name1, name2;
    //private ArrayList<Coordinate> moves;
    //private Coordinate move;
    private int playerNumber;
    Scanner in = new Scanner(System.in);
    Board bawd = new Board();
    Coordinate c = new Coordinate();
    Ship sh = new Ship();

    public Player(){}

    public void GetNames()
    {
        for(playerNumber = 1; playerNumber <= 2; playerNumber++)
        {
           System.out.print("Player " + playerNumber + ": ");
           name1 = in.nextLine();
           playerNumber++;
           System.out.print("Player " + playerNumber + ": ");
           name2 = in.nextLine();
           System.out.print("\033[2J");
        }
    }

    public void setShips()
    {
        bawd.singleP1View();
        sh.coordLoc();
        System.out.println("\033[2J");
        bawd.singleP2View();
        sh.coordLoc();
        System.out.println("\033[2J");
        game();
    }

    public void game()
    {
        bawd.p1turn();
        c.placeShip();
    }

}

shipPiece array未初始化。

更改

 public String [][] shipPiece;

 public String [][] shipPiece = new String [11][11];

這從未被初始化

public String [][] shipPiece;

你應該這樣初始化

public String [][] shipPiece = new String[10][10];

您永遠不會初始化shipPiece 您必須通過以下方式進行初始化:

public String [][] shipPiece = new String[11][11];
public String [][] shipPiece;

您沒有初始化這個壞男孩!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM