accessing last element in vector


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 6 of 6

Thread: accessing last element in vector

  1. #1
    Join Date
    Jul 2005
    Posts
    32

    accessing last element in vector

    Hi

    I have a vector and need to access the last element.

    My code for this is:

    Code:
    //  method to check if node which allows user to answer the question was visited 
    
    boolean nodeWithAnswerVisited(){ 
        if (userSearch.contains(optimalSearch.lastElement().toString())) return true; 
       else 
       return false; 
     } // end nodeWithAnswerVisited method
    I get the following error:

    NoSuchElementException.

    I have looked this up and can see it means the vector has no elements but it does - as I print these to the console to check.

    Any ideas where I am going wrong?

    Thanks in advance

  2. #2
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    You need to read the doc for the methods you are using.
    contains() takes an Object
    toString() returns a String object
    The question is: is THE String object returned by toString() contained in the Vector
    userSearch? Not another that has the same toString() value!

    What happens when you leave off the toString() call?

    For debugging, break the compound statement up into simple steps and do a println() after each. That can help.

  3. #3
    Join Date
    Jul 2005
    Posts
    32
    Hi Norm

    Thanks for your response. I did originally have it without the toString but it came up with the same error.

    However, for some reason, which I cannot see, the vector DOES appear to be empty at the point this method is called

    I have copied most of my code below in case someone can spot it for me - I have been looking for ages and cannot see why so would really appreciate any pointers on this.
    I have a method to reset the variables but the userSearch vector is OK and is cleared at the same time as the optimalSearch vector.

    Can anyone spot it?

    Thanks very much for any help on this!

    Code:
    //  method for finding optimalsearchpath
        public void moveSearchDown(int searchValue){
                if (searchValue > tempPointer.getValue()){ // if greater than current node, move to right subtree 
                	if (tempPointer.getRight() != null){ // if right subtree is not empty
                		tempPointer = tempPointer.getRight(); // move to right node
                		optimalSearch.add(new Integer(tempPointer.getValue())); // add node value to vector
                		moveSearchDown(searchValue); 
                        }
                }
                else if (searchValue < tempPointer.getValue()){ // if less than current node, move to left subtree
                    if (tempPointer.getLeft() != null){ // if left subtree is not empty
                		tempPointer = tempPointer.getLeft(); // move to right node
                		optimalSearch.add(new Integer(tempPointer.getValue())); // add node value to vector
                		moveSearchDown(searchValue);
                        }
                }
        } // end moveSearchDown method
        
        
        // method to build tree by inserting nodes and checking its depth is not too deep
        public void buildTreeContents(){
            randomNumber();      // call method for array of random numbers
    	    tn = new TreeNode(400,30,nums[0]);//constructor method for creating an object of TreeNode, use index 0 for the rootNode
    	       for (int i=1; i<amount; i++) {		 
    	           tn.insert(nums[i], tn.getParent());
    		   }
        } // end buildTreeContents method
       
     
        // method to generate tree 
        public void generateTree(){
            buildTreeContents();
    	        while (tn.treeDepth() > maxDepth){ //call the treeDepth method to check tree generated is not deeper than 4 levels
    	            System.out.println("TREE IS TOO DEEP!!!");
    	            buildTreeContents();	// if too deep generate and insert new tree
    		    }
    	    numberInTree(); // check if the node looking for is in the tree
    	    generateQuestion(); // generate question for user
    	    System.out.println("question node is " + question);
    	    torch = tn; // once have correct depth for tree, point torch to rootnode
    	    System.out.println("torch is pointing to " + torch.getValue());
    	    tempPointer = tn;  // also set up temporary pointer to the rootNode for finding optimal search path
    	    System.out.println("tempPointer is pointing to " + tempPointer.getValue());
    	    optimalSearch.add(new Integer(tempPointer.getValue()));  // add root node to userSearch vector.
    	    moveSearchDown(question); // call method to look for optimal value
    //      just debugging to see if anything goes into the vector!
    	    System.out.println("optimalSearch toString() is " + optimalSearch.toString());
    	    System.out.println("the optimalsearch is " + optimalSearch.size() + " steps.");
    	    //call the method to setup the Y coordinates for each node
    		tn.assignYCoordinate(0); 
            //call the workout boxes to setup the boxes for each node
    		tn.workOutBoxes(); 
    		// call the assignXcoordinate to setup X coordinates for each node
        	tn.assignXCoordinate(0); 
        } // end of generate tree
        
        
        //  method to check if node which allows user to answer the question was visited
        boolean nodeWithAnswerVisited(){ 
           	if (userSearch.contains(optimalSearch.lastElement())) return true;
        	else
        	    return false;
        } // end nodeWithAnswerVisited method
        
       
        //  method to determine the response to user when they click Node In Tree
        public void nodeInTreeResponseToUser(){ 
        	moveSearchDown(question);
            if (numberInTree() && nodeWithAnswerVisited()) { //correct and they did visit the node
        	    labelText = "<html><FONT COLOR=BLACK><p>Correct," + question + 
        		"is in the tree</p><p>You searched the nodes in this order:" + userSearch.toString() + 
        		"<br>That is " + userSearch.size() + " steps.</p><p>The optimal search path is this:<br>"
        		+ optimalSearch.toString() + "<br>That is " + optimalSearch.size() + " steps.</p></FONT<html>";
        	}
        	else if (numberInTree() && !nodeWithAnswerVisited()){ // correct but they didn't visit the node
        	   	labelText = "<html><FONT COLOR=BLACK><p>" + question + 
        		"is indeed in the tree,</p><p><p>BUT were you guessing?<br>You searched the nodes in this order:" + userSearch.toString() + 
        		"<br>This did not include finding " + question + "<p>The optimal search path is this:<br>"
        		+ optimalSearch.toString() + "<br>That is " + optimalSearch.size() + " steps.</p></FONT><html>";
        	}
        	else if (!numberInTree()){ // node isn't in the tree, must be guessing
        		labelText = "<html><FONT COLOR=BLACK><p>Incorrect," + question + 
        		" is not in the tree</p><p>You searched the nodes in this order:<br>" + userSearch.toString() + 
        		"<br>By searching the nodes in this order:<br> "; //+ optimalSearch.toString() + "<br>You could have realised at node </FONT>" + optimalSearch.lastElement().toString() + " that" + question + "could not be in the tree<html>";
        		System.out.println("optimalSearch vector from nodeInTreeResponseToUser() contains " + optimalSearch.toString());
        	}
        }// end of nodeInTreeResponseToUser method
    
    //  method to reset variables for each new search
        public void resetVariables(){
        	//stepsTaken = 0; //reset steps taken so that each time they generate a new tree it starts at zero
    	    userSearch.clear();  // empty vector for current search, ready for new search
    	    userSearch.add(new Integer(torch.getValue()));  // add root node to userSearch vector. Using new Integer as the vector only accepts objects 
           // stepsTaken = 1; // set stepsTaken to 1 so it includes the rootnode
    	    optimalSearch.clear();  // empty vector for current search, ready for new search
        } // end of resetVariables method
        
        
        public void drawWholeTree(Graphics2D g2) {  
    	    g2.setColor(new Color(153,153,153));  // lighter grey
    	    g2.fillRect(0,0,490,485);             // draw rectangle over the bufferedimage, setting x & y to 0 as its drawing directly onto buffered image
    	    tn.drawTree(g2, torch);               // draw all the nodes and connecting lines
        } // end drawWholeTree method

  4. #4
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    I don't see where the Vectors are defined?
    This is a logic problem which is more than I have time to unravel.
    If the Vector is empty, check why nothing is being added to it. Or if it is being cleared too soon. More println()s may be required to trace the logic flow.
    Good luck.

  5. #5
    Join Date
    Jul 2005
    Posts
    32
    Yeah, it is being added at one point, so I will try adding some printlns to each method to see if I can work out at which point it is getting cleared.

    Thanks anyway

  6. #6
    Join Date
    Jul 2005
    Posts
    32
    got it! It was the resetVariable button being called AFTER the optimalSearch vector had been populated. In the end I added a call to the method which populates the optimalSearch vector inside the resetVariables, straight after it has been cleared and it now works fine.

    Thanks again!

Similar Threads

  1. converting vector to xml
    By peter in forum Java
    Replies: 2
    Last Post: 02-28-2002, 04:07 PM
  2. AVL Tree element index
    By John in forum Java
    Replies: 2
    Last Post: 04-29-2001, 05:01 PM
  3. accessing a DOM tree element
    By joe crew in forum XML
    Replies: 0
    Last Post: 04-26-2001, 12:27 PM
  4. Vectors and Event handling
    By Attiq in forum Java
    Replies: 1
    Last Post: 11-05-2000, 08:34 PM
  5. Accessing element from Javascript
    By John Knoop in forum XML
    Replies: 0
    Last Post: 10-30-2000, 05:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center