Array index and item as drawn text

edited March 2018 in How To...

Hi guys,

Is there a way to have an array's indexes and items be drawn as text? I couldn't find anything specific on this and I'm a beginner to intermediate coder.

I've tried something like the following in the draw function: text("myArray indexes and items:" + myArray_name, 25, 25);

But the text that is drawn isn't anything I can understand. It seems like it's a hexadecimal number and not the familiar [0] item0 , [1] item1, [2] item2, [n] itemn format.

Do I need to do some sort of conversion where the array is transformed in to a String before it goes into the text()?

Thanks for the help!

Answers

  • edited March 2018

    It seems like it's a hexadecimal number

    you're trying to print a complex object, an array, and there's no toString() defined so it prints the default java reference (which is a memory reference a hash)

    to print out the entire array you need to iterate over it yourself.

  • edited March 2018

    try it with a for loop :

    for ( int i; i<arrayMy.length; i++) {
    
          text(arrayMy[i], 30, 18+ 22*i);
    
    }
    
  • edited March 2018

    If the datatype of your 1D array isn't any of the 8 Java primitives, you can use this utility function makeArrayPrintable() I've made for some old post as a starting point: :\">

    https://Forum.Processing.org/two/discussion/24337/the-table-has-no-column-named#Item_9

    @ SafeVarargs static final String makeArrayPrintable(final Object... arr) {
      if (arr == null || arr.length == 0)  return "";
      final StringBuilder sb = new StringBuilder();
    
      for (final Object obj : arr)  sb.append(obj).append(ENTER);
      return sb.substring(0, sb.length() - 1);
    }
    

    It just needs some extra code for including the index too. #:-S

    In case your 1D array turns out to be 1 of the 8 Java primitives, simply replace each Object in the code above w/ the desired primitive datatype. :ar!

  • edited March 2018

    BtW, makeArrayPrintable() is pretty much similar to join(): :\">
    https://Processing.org/reference/join_.html

    Of course, makeArrayPrintable() is much more flexible for the datatypes it can accept and potentially more customizable for its output String. \m/

Sign In or Register to comment.