简体   繁体   中英

Java Two-Dimensional Array

The two-dimensional array of boolean values that will be referenced by matrix will be used to simulate an LED-based display that can hold LETTERS_PER_DISPLAY letters.

Modify the constructor to create a two-dimensional array of boolean that has FONT_LETTER_HEIGHT rows and (FONT_LETTER_WIDTH times LETTERS_PER_DISPLAY) columns and assign it to the instance variable matrix.

public class LEDDisplay
{
   private boolean[] = matrix;
   private static final int FONT_LETTER_HEIGHT = 5;
   private static final int FONT_LETTER_WIDTH = 6;
   private static final int LETTERS_PER_DISPLAY = 10;

public LEDDisplay()
{
    boolean[][] matrix = new boolean[FONT_LETTER_HEIGHT][FONT_LETTER_WIDTH]
}

Please could you tell me whether my constructor is correct?

it's actually not correct - you hide the member variable matrix by defining a local to the constructor one. Here is the correct way:

public class LEDDisplay
{
   private boolean[][] matrix;
   private static final int FONT_LETTER_HEIGHT = 5;
   private static final int FONT_LETTER_WIDTH = 6;
   private static final int LETTERS_PER_DISPLAY = 10;

public LEDDisplay()
{
    matrix = new boolean[FONT_LETTER_HEIGHT][FONT_LETTER_WIDTH * LETTERS_PER_DISPLAY];
}

Your one dimentional array matrix is class variable whereas matrix in constructor is local to the constructor and not visible outside the constructor.

FONT_LETTER_HEIGHT rows and (FONT_LETTER_WIDTH times LETTERS_PER_DISPLAY) columns

That should be:

new boolean[FONT_LETTER_HEIGHT][FONT_LETTER_WIDTH * LETTERS_PER_DISPLAY]

and assign it to the instance variable matrix.

public LEDDisplay()
{
    matrix = new boolean[FONT_LETTER_HEIGHT][FONT_LETTER_WIDTH]
}

However

boolean[][] matrix = new boolean[FONT_LETTER_HEIGHT][FONT_LETTER_WIDTH]

creates a local variable matrix that is visible only in the constructor. This will have no effect on the instance variable matrix .

Two small probs with the code:

  1. matrix is defined as a member variable of the class, should be defined as a 2-D array, and then does not need to be re-defined in the constructor

  2. the original post states that there should be

"(FONT_LETTER_WIDTH times LETTERS_PER_DISPLAY) columns"

and your constructor only includes FONT_LETTER_WIDTH

Something like this:

public class LEDDisplay
{
   private boolean[][] matrix;
   private static final int FONT_LETTER_HEIGHT = 5;
   private static final int FONT_LETTER_WIDTH = 6;
   private static final int LETTERS_PER_DISPLAY = 10;

public LEDDisplay()
{
    matrix = new boolean[FONT_LETTER_HEIGHT][FONT_LETTER_WIDTH * LETTERS_PER_DISPLAY];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM