无法通过2 dim java数组打印字符

时间:2013-12-10 06:24:50

标签: java arrays

我尝试将此代码作为分数表运行,其中我有字符和下标用于标题;

     A     B     c
1
2         65      //this is where I'm stuck again!
3

为了在特定的地方(矩阵)打印上面的(65)得分,但是一旦我尝试添加打印语句,表就会崩溃。任何帮助将不胜感激;

public class Table3 {
    static int[][] list = new int[4][4];
    //private char column = 'A';
    //private int row = 1;
    private static int row = 1;
    public Table3(){
        //column = 'A';
        for (int i = 0; i < 4; i++) {  
            for (int j = 1; j < 4; j++)
                list[i][j] = 0;
        }
        }

    public static void table(char col, int row, int value) {
        //System.out.printf("\n\n%s\n", "Table");

        for (int i = 1; i < 4; i++) {
            System.out.print(row + "     ");
             row++;
            for (int j = 1; j < 4; j++)System.out.print(col + "     ");   
               System.out.println("\n");       
                   col++;
                if (row >= 0 && row <= 4 && col >=0 && col <= 4) 

                System.out.print(list[col][row]=value);
            System.out.println("\n");
        }
    }
}

客户端

public class TableTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Table3 t = new Table3();
        t.table('A', 5, 5);


    }
}

1 个答案:

答案 0 :(得分:0)

了解如何使用System.out.printf。文档为here

public class Table3
{
    static int numRows = 4;
    static int numCols = 4;
    static int[][] list = new int[numRows][numCols];

    public Table3()
    {
        //column = 'A';
        for (int i = 0; i < 4; i++)
        {
            //this is the row number so you don't have to print it manually
            //just print the array
            list[i][0] = i;

            //initialize the list to 0
            for (int j = 1; j < 4; j++)
            {
                list[i][j] = 0;
            }
        }
    }

    public static void table(char col, int row, int value)
    {
        list[row][col] = value;

        int columnWidth = 5;  //in characters

        //empty space before first column header
        for (int i = 0; i < columnWidth; i++)
        {
            System.out.print(" ");
        }

        //print the column headers (A through C)
        for (int i = 1; i < numCols; i++)
        {
            System.out.printf("%-" + columnWidth" + "c", (char)(64 + i));
        }
        System.out.println();   //get off of the column header row

        //print the rest of the table
        for (int i = 1; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                if (list[i][j] == 0)
                {
                    System.out.printf("%" + columnWidth + "s", " ");
                }
                else
                {
                    System.out.printf("%-" + columnWidth + "d", list[i][j]);
                }
            }
            System.out.println("\n");
        }
    }
}