如何将2D Int数组转换为字符串

时间:2017-11-16 16:54:40

标签: java arrays string int

尝试创建一个基本的战舰游戏

   import java.util.*;
   import java.util.Scanner;
   public class BattleShip
   {
      Scanner input = new Scanner(System.in);
      //public static final boolean DEBUG = false;
      public static void breakln()
      {

   }


      public static void main(String[] arg)
      {
          int size = 0;   
          int[][] board = new int[5][5];
         createBoard(board);
         createShip(board, 4);
         BattleShip.createBoard(board);
         BattleShip.Display_Baord(board);
         BattleShip.createShip(board, size );

      }



      public static void createBoard(int[][] board){
          for(int row=0 ; row < 5 ; row++ )
              for(int column=0 ; column < 5 ; column++ )
                  board[row][column]=-1;
      }

      public static void Display_Baord(int[][] board){
          System.out.println("\t1 \t2 \t3 \t4 \t5");
          System.out.println

();

          for(int row=0 ; row < 5 ; row++ ){
              System.out.print((row+1)+"");
              for(int column=0 ; column < 5 ; column++ ){
                  if(board[row][column]==-1){
                      System.out.print("\t"+"~");
                  }else if(board[row][column]==0){
                      System.out.print("\t"+"*");
                  }else if(board[row][column]==1){
                      System.out.print("\t"+"X");
                  }

              }
              System.out.println();
          }

      }



      This is the method where the error is 

      public static void createShip(int[][] board,int size)
      {
         if(Math.random() < 0.5)
         {
            int col = (int)(Math.random()*5);
            int row = (int)(Math.random()*7);
            for(int i = 0; i<size; i++)
            {
               board[row][col+i] = "S"; Hear is my error, i cannot have 's' as my 2d array ' board is an int
            }
         }
         else
         {
            int col = (int)(Math.random()*7);
            int row = (int)(Math.random()*5);
            for(int i = 0; i<size; i++)
            {
               board[row+i][col] = "S";    Hear is my error, it cannot be a string as 'board' is an int 
            }
         }
      }
   }

我只是想知道如何存储&#39;&#39;在我的int 2D数组板中。

1 个答案:

答案 0 :(得分:0)

而不是使用&#34; S&#34;在int数组中,使用一个int,你几乎可以在以后提取它作为标志。

例如,您似乎没有使用负数。

而不是使用&#34; S&#34;,-1呢?

然后在你的代码中而不是检查&#34; S&#34;稍后,您可以检查-1,而不必担心转换整个阵列。