Results 1 to 3 of 3
  1. #1
    new Object() is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Exclamation Problems with method which returns result

    public T getElement(){
    T result = null;
    int index = 0;
    if (usedElements > 0){
    index = new Random().nextInt(data.length);
    result = (T)data[index];

    if (data[index] == null){getElement();}
    removeElemet((T)data[index]);
    }
    return result;
    }

    Hello there.

    I have cuted one fragment of my program, the main idea is to take elements from array randomly and then delete them. removeElement(); searches for element in array and deletes it after it is randomly chosen by getElement();
    After removeElement(); control goes to return function which must return result, but sometimes return gives control back to " if (data[index] == null){getElement();} ", it happens randomly, is there any explanation of such?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,798
    Rep Power
    19

    Default

    Use code tags when posting code, please.
    Makes things easier to read.
    Java Code:
    public T getElement(){
        T result = null;
        int index = 0;
        if (usedElements > 0) {
            index = new Random().nextInt(data.length);
            result = (T)data[index];
    
            if (data[index] == null) {
                getElement();
            }
            removeElemet((T)data[index]);
        }
        return result;
    }
    That return statement cannot result in the flow going to the earlier if statement.
    So something else is going on.

    Stick a ton of println()s in there so you can follow the flow.

  3. #3
    new Object() is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Default

    Solved problem by adding if (data[index] == null) {return getElement();}

Similar Threads

  1. Replies: 5
    Last Post: 10-30-2010, 12:05 AM
  2. Replies: 2
    Last Post: 10-15-2010, 05:09 AM
  3. Method problems
    By Turismo in forum New To Java
    Replies: 8
    Last Post: 07-18-2010, 06:57 AM
  4. Problems with method
    By ai_2007 in forum Advanced Java
    Replies: 1
    Last Post: 06-28-2007, 06:49 PM
  5. Problems with Find method in EJB
    By Nick15 in forum Enterprise JavaBeans (EJB)
    Replies: 0
    Last Post: 05-14-2007, 01:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •