打印10 x 10坐标网格

时间:2014-11-26 15:26:11

标签: java arrays loops

我正在打印一个网格,对于列显示0到9,对于行显示0到9。

我想将它显示为0 - 9表示列,A - J表示行,但我不确定如何在循环中使用字符而不是整数?

public class BattleshipGame {

private char[][] playerBoard;   
private char[][] compBoard;     
private final static int boardSize = 10;
private String input, shipType, shipDirection = ""; 
public static String name;      
private int shipRowLoc, shipColLoc; 
private boolean allowed, random = false, showShips = false;
private MoveType moveType;
private ArrayList<Battleships> enemyShips = new ArrayList<Battleships>();

Scanner userinput = new Scanner(System.in);

public BattleshipGame() {
    playerBoard = new char[boardSize][boardSize];
    compBoard = new char[boardSize][boardSize];
    initializeBoard();  
    placeShip();    
}

public void initializeBoard() {
    for (int i = 0; i < boardSize; i++)
        for (int j = 0; j < boardSize; j++){
            playerBoard[i][j] = '~';
            compBoard[i][j] = '~';
    }
}

2 个答案:

答案 0 :(得分:3)

你有几个选择,你可以使用

for (char ch = 'A'; ch <= 'J'; ch++)

或类似

for (int j = 0; j < 10; j++) {
  char ch = (char) ('A' + j);

答案 1 :(得分:1)

要从A映射字符J - int,您可以在代码点对它们进行索引。

例如,A65

因此System.out.println((char)65)将打印A

将您的索引从0增加到9,然后您就可以获得AJ的字符。