打印出2D数组中的列

时间:2014-12-08 02:01:24

标签: java

我的打印方法没有打印出所有列。它只打印出一半的列,但它打印出所有行。

如何更改我的打印方法以打印出所有列?

import java.io.*;
import java.util.Scanner;

public class T_GameOfLife {
  private char[][] board;
  private int columns;
  private int rows;
  private int generation;

  public static void main(String[] args) throws FileNotFoundException {
    T_GameOfLife game = new T_GameOfLife();
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter how many generations to compute: ");
    int gen = keyboard.nextInt();
    System.out.println("Generation 1:");
    game.print();

    for (int i = 2; i <= gen; i++) {
      System.out.println("Generation " + i);
      game.computeNextGeneration(gen);
      game.printNew();
    }
  }

  public T_GameOfLife() throws FileNotFoundException {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter file name: ");
    String filename = keyboard.nextLine();
    File file = new File(filename);
    Scanner inputFile = new Scanner(file);
    int columns = inputFile.nextInt();
    int rows = inputFile.nextInt();
    inputFile.nextLine();
    board = new char[rows][columns];

    for (int i = 0; i < rows; i++) {
      String line = inputFile.nextLine();
      for (int j = 0; j < columns; j++) {
        board[i][j] = line.charAt(j);
      }
    }
  }

  public int getColumns() {
    return columns;
  }

  public int getRows() {
    return rows;
  }

  public int getCell(int rows, int columns) {
    if (board[rows][columns] == 'X' || board[rows][columns] == '0') {
      return board[rows][columns];
    } else {
      return 0;
    }
  }

  public void setCell(int rows, int columns, int value) {
    for (int i = 0; i < board.length; i++) {
      for (int j = 0; j < board[0].length; j++) {
        value = board[rows][columns];
      }
    }
  }

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

2 个答案:

答案 0 :(得分:0)

您的setCell函数似乎无能为力。我想你打算写:

board[rows][columns] = value;

而不是你现在拥有的。

就打印部分而言,您的功能是打印出所有的行和列,因此可能是电路板上有一半是空的或不可打印的字符。

答案 1 :(得分:0)

根据您在其他解决方案中的有趣对话,您可能需要在继续此Java编程冒险之前查看edx或coursera的编程课程简介...

尽管如此......

board[rows][columns] = value;

是你想要的,否则setcell什么都不做。精度的错误是指你的董事会使用char,而你的值被声明为int,即type错误。

对于打印循环,我无法推断出任何内容,但您可能想尝试使用'rows'和'columns'而不是.length