The declaration in "Action 2" is creating a NEW LOCAL VARIABLE called table that is shadowing the global member variable called table.

computer science

Description

Many of you are doing something like this:

public boolean buildTable(int offset){

    //Action 1: Here the code checks if offset is not valid and returns false if invalid

    //Action 2: Here people make a table doing something like:

    //  char[][] table = new char[2][26];

    //Action 3: Here the code adds 'a', 'b', ..., 'z' to the top row

    //Action 4: Here the code calls getCipherLetter to get the letters

    //  for the second row.

    //Action 5: if everything went well return true.

  }

That is VERY WRONG!

The problems are as follows: 

·         The declaration in "Action 2" is creating a NEW LOCAL VARIABLE called table that is shadowing the global member variable called table. The offending code is this one: char[][] table. That is a declaration of a new local variable also called table.  Once the method is done, that local variable table is dead and gone and that table is now trash. That means you cannot print it or use it for encrypting or decrypting because those actions require the global table to be filled up and available.

·         Even if you assigned the space correctly by only doing an assignment to the current variable table (without redeclaring it) : 

o    table = new ... //note there is no redeclaration, only assignment

o    You would be ALWAYS overwriting table each time you call, which is inefficient. You should only do this if it does not already exist and then proceed to fill up the second row. This, however, is an optimization that we will not enforce.

 


Related Questions in computer science category