How to get x value from the last index in PVector ArrayList?

edited February 2017 in Questions about Code

Hi fellows! :-h

I am trying to get in console x value from the last index in PVector ArrayList? VIDEO

ArrayList locations = new ArrayList();

void setup() {
  size(640, 360);
  locations.add( new PVector (width/2, height/2) );
  
}
void draw() {
  background(0);
  println(locations);
}

void mousePressed() {
  locations.add( new PVector (mouseX, mouseY) );
}

With this code above I am getting in console for each PVector x, y and z values. If I change println(locations); into println(locations.get(locations.size()-1)); I am getting only x,y and z values from the LAST PVector.

Now my question is how can I get from the last PVector x value?

This line of code println(locations.get(locations.x.size()-1)); gives me an error message "The global variable x does not exist."

Tagged:

Answers

  • edited February 2017

    println( locations.get(locations.size() - 1).x );

    https://Processing.org/reference/dot.html

  • Thanks for the reference, however this code

    println( locations.get(locations.size() - 1).x );

    gives me the same error as

    println(locations.get(locations.x.size()-1));

    "The global variable x does not exist."

    "x cannot be resolved or is not a field"

    VIDEO

  • Answer ✓

    your arraylist isn't typed, so the compiler doesn't know what it contains.

    you can either define your arraylist as containing pvectors

    ArrayList<PVector> locations = new ArrayList<PVector>();
    

    or you can tell it what you've extracted at the point of extraction

    PVector last = (PVector)locations.get(locations.size() - 1);
    println(last.x);
    

    the former is preferable.

  • Thank you.

  • edited February 2017

    It's a good idea to 1st read the reference about the feature you're trying to use: ;)
    https://Processing.org/reference/ArrayList.html

    import java.util.List;
    final List<PVector> locations = new ArrayList<PVector>();
    
    locations.add( new PVector (width>>1, height>>1) );
    println( locations.get(locations.size() - 1).x );
    
    exit();
    
Sign In or Register to comment.