views:

69

answers:

2

Note: This is an assignment

Hi,

I have the following class/constructor.

import java.io.*;

class Set {

       public int numberOfElements = 0;
       public String[] setElements = new String[5]; 
       public int maxNumberOfElements = 5;

       // constructor for our Set class   

       public Set(int numberOfE, int setE, int maxNumberOfE) {
          int numberOfElements    = numberOfE;
          String[] setElements    = new String[setE];
          int maxNumberOfElements = maxNumberOfE;
       }

       // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :(

       static String[] removeAt(int k, String[] arr) {
           final int L = arr.length;
           String[] ret = new String[L - 1];
           System.arraycopy(arr, 0, ret, 0, k);
           System.arraycopy(arr, k + 1, ret, k, L - k - 1);
           return ret; 
       }

       int findElement(String element) {
          int retval = 0;

            for ( int i = 0; i < setElements.length; i++) {

               if ( setElements[i] != null && setElements[i].equals(element) ) {
                  return retval = i;

               }
            retval = -1; 
           }

          return retval;
       }

       void add(String newValue) {
            int elem = findElement(newValue);
            if( numberOfElements < maxNumberOfElements && elem == -1 ) {
               setElements[numberOfElements] = newValue;
               numberOfElements++;
            } 
       }

       int getLength() {
           if ( setElements != null ) {
                return setElements.length;
           }
           else {
                return 0;
           }
       }

       String[] emptySet() {
          setElements = new String[0];
          return setElements;
       }


      Boolean isFull() {
           Boolean True = new Boolean(true);
           Boolean False = new Boolean(false);
          if ( setElements.length == maxNumberOfElements ){
                return True; 
          } else { return False; }
       }

      Boolean isEmpty() {
            Boolean True  = new Boolean(true);
            Boolean False = new Boolean(false);

            if ( setElements.length == 0 ) {
                return True;
            } else {  return False; }
       }

       void remove(String newValue) {

            for ( int i = 0; i < setElements.length; i++) {
               if ( setElements[i].equals(newValue) ) {
                    setElements = removeAt(i,setElements);

               }
            }

       }   

        int isAMember(String element) {
           int retval = -1;

           for ( int i = 0; i < setElements.length; i++ ) {
                if (setElements[i] != null && setElements[i].equals(element)) {
                     return retval  = i;
                }   
           }
           return retval;
       }

       void printSet() {
            for ( int i = 0; i < setElements.length; i++) {
               System.out.println("Member elements on index: "+ i +" " + setElements[i]);
            }
       }

       String[] getMember() {
            String[] tempArray = new String[setElements.length];
            for ( int i = 0; i < setElements.length; i++) {
               if(setElements[i] != null) {
                    tempArray[i] = setElements[i];
               }
            }
            return tempArray;
       }

       Set union(Set x, Set y) {
          String[] newXtemparray = new String[x.getLength()];
          String[] newYtemparray = new String[y.getLength()];
          Set temp = new Set(1,20,20);
          newXtemparray = x.getMember();
          newYtemparray = x.getMember();
          for(int i = 0; i < newXtemparray.length; i++) {
               temp.add(newYtemparray[i]);
          }

          for(int j = 0; j < newYtemparray.length; j++) {
               temp.add(newYtemparray[j]);
          }
          return temp;
       }

}

// This is the SetDemo class that will make use of  our Set class

class SetDemo {
     public static void main(String[] args) {
          //get input from keyboard
          BufferedReader keyboard;
          InputStreamReader reader;
          String temp = "";

          reader =   new InputStreamReader(System.in);
          keyboard = new BufferedReader(reader);


      try 
          {
               System.out.println("Enter string element to be added" );
               temp = keyboard.readLine( );
               System.out.println("You entered " + temp );
          }
     catch (IOException IOerr)
          {
               System.out.println("There was an error during input");
          }

     /* 
      **************************************************************************
      * Test cases for our new created Set class.
      *
      **************************************************************************
     */
     Set setA = new Set(1,10,10);
     setA.add(temp);
     setA.add("b");
     setA.add("b");
     setA.add("hello");
     setA.add("world");
     setA.add("six");
     setA.add("seven");
     setA.add("b");
     int size = setA.getLength();
     System.out.println("Set size is: " + size );
     Boolean isempty = setA.isEmpty();
     System.out.println("Set is empty? " + isempty );
     int ismember = setA.isAMember("sixb");
     System.out.println("Element six is member of setA? " + ismember );
     Boolean output = setA.isFull();
     System.out.println("Set is full? " + output );
     setA.printSet();
     int index   = setA.findElement("world");
     System.out.println("Element b located on index: " + index );
     setA.remove("b");
     setA.emptySet();
     int resize = setA.getLength();
     System.out.println("Set size is: " + resize );
     setA.printSet();
     Set setB = new Set(0,10,10);
     Set SetA = setA.union(setB,setA);
     SetA.printSet();
     }
}

I have two question here, why I when I change the class property declaration to:

class Set {

       public int numberOfElements;
       public String[] setElements; 
       public int maxNumberOfElements;

       // constructor for our Set class   

       public Set(int numberOfE, int setE, int maxNumberOfE) {
          int numberOfElements    = numberOfE;
          String[] setElements    = new String[setE];
          int maxNumberOfElements = maxNumberOfE;
       }

I got this error:

\

javaprojects>java SetDemo
Enter string element to be added
a
You entered a
Exception in thread "main" java.lang.NullPointerException
        at Set.findElement(Set.java:30)
        at Set.add(Set.java:43)
        at SetDemo.main(Set.java:169)

Second, on the union method, why the result of SetA.printSet still printing null, isn't it getting back the return value from union method?

Thanks in advance for any explaination.

lupin

+5  A: 

You're shadowing your instance variables in the constructor:

When you write:

   public Set(int numberOfE, int setE, int maxNumberOfE) {
      int numberOfElements    = numberOfE;
      String[] setElements    = new String[setE];
      int maxNumberOfElements = maxNumberOfE;
   }

That creates three new variables all of which only last the duration of the constructor. It should be:

   public Set(int numberOfE, int setE, int maxNumberOfE) {
      this.numberOfElements    = numberOfE;
      this.setElements    = new String[setE];
      this.maxNumberOfElements = maxNumberOfE;
   }

You can drop the this. in this second version, but I find it clearer (it also lets you reuse variable names).

Also, you don't need to do:

      String[] newXtemparray = new String[x.getLength()];
      String[] newYtemparray = new String[y.getLength()];
      Set temp = new Set(1,20,20);
      newXtemparray = x.getMember();
      newYtemparray = x.getMember();

Just:

      Set temp = new Set(1,20,20);
      String[] newXtemparray = x.getMember();
      String[] newYtemparray = y.getMember();

is fine (note you also had a typo for newYtemparray; it was x.getMember)

These are reference variables. Currently, you're initialize them each to point to a new array. Then immediately, you assign them to point to a different array. So you're needlessly allocating and destructing memory.

Matthew Flaschen
this works, thanks.
lupin
@lupin - mark this answer as accepted then (tick below the vote counter)
Bozho
A: 

Maybe because you forget about hiding? You don't assign any values to class vars in constructor, you just create new objects, which are garbage collected after constructor ends. Look for "scopes" or "visibility" for further info.

foret