0
int[] numbers = new int[10];
numbers[0] = 20;

At first I thought I was so far off in syntax (I'm more of a C++ programmer), that It wouldn't work. But I whipped out the good ole' Java book and this would be correct.

Is there any obvious reason why Android Studio isn't recognizing this? The first line declaring the array appears to work properly, but the line where I set 20 as the first block is giving me the red squigglies and Unknown Class 'numbers' error.

2
  • 2
    Show us the full code reproducing the issue Commented Feb 11, 2015 at 6:40
  • adding brackets around numbers[0] = 20; can help ) Commented Feb 11, 2015 at 6:41

4 Answers 4

3

This is what happens if the code is in a class body and not in a method body.

The declaration on the first line is valid in both class and method bodies. The second line assignment is only valid in a method.

Sign up to request clarification or add additional context in comments.

3 Comments

le sigh I see this now. I'd like to blame it on my lack of Java, but somehow I still feel like I should have been able to pick up on this. Nonetheless, thanks for taking the time to point that out.
For what it's worth, the situation is the same in C++. You can only have declarations in a class {} block, code such as assignments need to be in function blocks. The compiler expects to see a declaration and emits an error message when the "declaration" has unknown type.
Well right, I was definitely declaring inside the activity's public class brackets. It took me putting it inside a function/method inside the class to be able to pull it off.
0

Your second line needs to be inside a method (function).

class Foo
{
    int numbers[] = new int[10];

    Foo()
    {
         numbers[0] = 20;
    }
 }

Comments

0

You should assign values in constructor or in some method...

Comments

-1

If you are coding for Android then ArrayList is more preferable and easy to use too,

As simple as

ArrayList numbers=new ArrayList();

numbers.add(20);

2 Comments

This doesn't answer the problem in question though.
While I have to agree with the above statement (it doesn't necessarily answer my original question), I do appreciate the advice. I looked into the differences, and as far as I can tell, unless there's a true need to switch to ArrayList which I can't seem to find at this point, I'll stick with array. Again, thanks for the honest advice though. I'm not big on Java, and I'm definitely new to Android.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.