Cannot convert Object to Object[]

edited March 2018 in Questions about Code

Hello all! Very basic question and I'm sure the answer will be obvious as soon as it's pointed out but I've scoured this forum and Google and am still running into errors. I'm trying to append a random string from an array to another array and having issues with miscast objects.

Using the append reference example to break down my project at its simplest core:

Object[] sa1 = { "OH", "NY", "CA"}; 
Object[] sa2 = {"MA", "ME"};
int rand = (int)random(sa2.length);
Object[] sa3 = append(sa1, sa2[random]);

println(sa3);

What I'm trying to do is print sa1 and every time the program runs, have only one of the elements in array sa2 be appended at the end. I've tried different iterations and run into various errors. At this point, the error I get is: Cannot convert Object to Object[].

Would really appreciate some pointers. Apologies for the extremely basic question -- my search skills are clearly not up to snuff.

Tagged:

Answers

  • edited March 2018
    int rand = (int)random(sa2.length);
    Object[] sa3 = append(sa1, sa2[random]);
    

    You're using random() as an index variable here: sa2[random] #-o
    Also you shouldn't declare your variables w/ Object datatype! [-X

  • Thanks for the feedback! I was trying a ham fisted way of avoiding the String datatype to see if that was the issue the first time.

    This ended up working out for me, in case anyone else needs this in the future.

    String[] sa1 = { "OH", "NY", "CA"}; 
    String[] sa2 = {"MA", "ME"};
    int rand = int(random(sa2.length));
    
    println(append (sa1,(sa2[rand])));
    
  • edited March 2018 Answer ✓
    final String[] sa1 = { "OH", "NY", "CA" }, sa2 = { "MA", "ME" };
    final String[] sa3 = append(sa1, sa2[ (int) random(sa2.length) ]);
    
    println(sa3);
    exit();
    
  • Thank you! Much cleaner and I learned something. Just to clarify after reading the reference, 'final' makes it so 'sa1', 'sa2', and 'sa3' are only going to be assigned to those String arrays/ functions, right?

  • edited March 2018 Answer ✓

    For variables, final means we can't use any assignment operator = for that variable anymore: :-B
    https://Processing.org/reference/final.html

  • Thanks for the clarification!

Sign In or Register to comment.