I'm working in Netbeans and I've got just a bit of code that's not doing what it should be doing:
What Netbeans is telling me is that the "cardList = new String;" line and every line after it has the following error: "cannot find symbol: symbol: class cardList location: class Security <identifier> expected"
What the hey? Based on the coloring of variables that Netbeans does, the first use of cardList is not related to any of the other uses of cardList. Just to make sure there were no weird hidden characters, I've copied and replaced all of the occurrences of cardList.
I know that it must be simple, but what am I doing wrong here?
Thanks in advance for any help that you can provide...
You might want to start with the simplest piece of runnable Java code, which looks like this:
While you can define variables at a class level, such as numCards, and cardList, your behavioural code needs to be written inside a method. So to correct the structure of your code you would have something like this:
Now, all that does is create a 5 element array of type String and put 5 Strings in it. I expect the next step would be to have the program display the content of the array back at you? Have a go.
So it turns out that my problem was that I was trying to do too much in a class, but outside of a method. Simply moving the offending lines of code inside of a method made my errors go away.
However, this does bring up an interesting question.
In Java, if I wanted to load up an array as a "global variable" within a class, could I do it outside of method? Or in Java is creating and loading an array with values something that is always going to have to be done inside of a method? If I load it in a method, is it still a global variable inside of the class?
You can declare a variable, or you can declare and initialize a variable, but you can't just initialize a variable outside of a method, constructor, or static block. Arrays can be declared and initialized like this:
All things are lawful, but not all things are profitable.
Yes, you can find quite a nice Getting Started Tutorial over at the Official Oracle Java Tutorial site that explains the basic structure of a Java source file and what goes where.
As for the other question, the answer is yes to all of it.
You can declare and initialise a class level variable (sometimes called a field or member) in the same place as long as you can do it in a single statement. For example:
Notice you have visibility of cardList from within the method, and you will have visibility of cardList in all methods contained in the class Security. Java variables are mutable by default so you could load the values in a method as demonstrated in my previous post. Those changes will be observed by all methods that have access to the variable.