有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Tictaoe打印电路板

我正在尝试创建一个Tictatcoe游戏,但想问一个问题。我有一个2d char数组,现在填充的是下划线-'_'。我的问题是如何在每行输出三个下划线?提前谢谢

import java.util.Scanner;
import java.util.*;
public class TicTacToe {

    public static void main(String[] args){
        Scanner kbd = new Scanner(System.in);

        char[][] theBoard = new char[3][3];

        for(int i = 0; i < theBoard.length; i++){
            for(int j = 0; j < theBoard[i].length; j++){
                theBoard[i][j] = '_';
            }
        }

        for(int i = 0; i < theBoard.length; i++){
            for(int j = 0; j < theBoard[i].length; j++){

                System.out.print(theBoard[i][j] + " ");
            }
        }
    }



}

共 (3) 个答案

  1. # 1 楼答案

    您可以简单地执行以下操作:

    for(int i = 0; i < theBoard.length; i++){
         for(int j = 0; j < theBoard[i].length; j++){
              System.out.print(theBoard[i][j] + " ");
         }
         System.out.println(); // add this
    }
    

    此外,手动填充数组可能比使用for循环更快(略快)。e、 g

    char[][] theBoard = new char[][]{{'_', '_', '_'}, {'_', '_', '_'}, {'_', '_', '_'}};
    

    当一个简单的语句就可以了时,不需要复杂的逻辑!:)

  2. # 2 楼答案

    按如下方式修改您的代码:

        for(int i = 0; i < theBoard.length; i++){
            for(int j = 0; j < theBoard[i].length; j++){
    
                System.out.print(theBoard[i][j] + " ");
            }
            System.out.println();
        }
    

    这样,在一行完成后,您将移动到新行

    更新

    另一种办法是:

        for(int i = 0; i < theBoard.length; i++){
            StringBuffer buf = new StringBuffer();
            for(int j = 0; j < theBoard[i].length; j++){
                buf.append(theBoard[i][j] + " ");
            }
            System.out.println(buff.toString());
        }
    
  3. # 3 楼答案

    我相信是的

    if ((j + 3) % 3 == 0)
    

    系统。出来println()